`I'm working on a WordPress project where I need to dynamically change the page template of a post based on a custom field value. For example, if a custom field named "page_template" is set to "template-1.php" for a post, I want that post to use "template-1.php" as its page template instead of the default template assigned to the post type.
1 Answer
There is a WP filter hook that basically decide which template file to load.
add_filter( 'template_include', function( $template ) {
if ( is_single() ) {
global $post;
$meta_value = get_post_meta( $post->ID, 'page_template', true);
if( $meta_value == "template-1.php" ) {
return locate_template( array( 'template-1.php' ) );
}
}
return $template;
},99);