0

`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 1

0

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.