In the latest version of Portfolio Press I decided to move all the custom page templates into their own “templates” directory. This helps to organize the files better and simplifies the directory. However, I also needed to build an update routine for existing users who had the page templates set at the previous paths
To do that, I needed to query for all pages that had a page template set, check if matched one of my existing templates, and then update it to the new path. Here’s the code snippet in case it is useful to anyone else.
/**
* Part of the Portfolio Press upgrade routine.
* The page template paths have changed, so let's update the template meta for the user.
*/
function portfoliopress_update_page_templates() {
$args = array(
'post_type' => 'page',
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => '_wp_page_template',
'value' => 'default',
'compare' => '!='
)
)
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) :
while ( $query->have_posts() ) : $query->the_post();
$current_template = get_post_meta( get_the_ID(), '_wp_page_template', true );
$new_template = false;
switch ( $current_template ) {
case 'archive-portfolio.php':
$new_template = 'templates/portfolio.php';
break;
case 'full-width-page.php':
$new_template = 'templates/full-width-page.php';
break;
case 'full-width-portfolio.php':
$new_template = 'templates/full-width-portfolio.php';
break;
}
if ( $new_template ) {
update_post_meta( get_the_ID(), '_wp_page_template', true );
}
endwhile;
endif;
}