how to assign page template dynamically in wordpress

I have a WordPress page created dynamically

$my_post = array(
        'post_title' => 'page-for-download',
        'post_content' => '',
        'post_status' => 'publish',
        'post_author' => 1,
        'post_type' => 'page'

    );

now my question is how to assign page template to this page dynamically

Related posts

Leave a Reply

1 comment

  1. WordPress keeps the page template in a post meta entry(named _wp_page_template). Here is what you should do once you create the page:

    update_post_meta( $new_post_id, '_wp_page_template', 'custom-template.php' );
    

    Where $new_post_id is the result of wp_insert_post()(I assume that this is what you are using to create the new post). Note, that you might want to check to see if you have an actual id(by default wp_insert_post() will return false if it fails to create a new post).

    You can see that information in the first NOTE in the Parameters section of the WordPress codex page Function Reference/wp insert post