Page not using template given to wp_insert_post()

I’ve created a new page with the code below:

$my_post = array(
    'post_content'   => "My page content", 
    'post_title'     => "Page for product 1234", 
    'page_template'  => "listing.php"
);
$post_id = wp_insert_post( $my_post );
echo "<br /> ID returned from wp_insert_post is $post_id"; 

I tried in the array to make the page use “listing.php” as the template but when I put http://example.com/?p=61 into my browser address bar, where 61 is the $post_id returned by wp_insert_post() above, the page is found but it’s using “single.php” as the template.

Read More

Why didn’t it use “listing.php”, and how can I make it use “listing.php”?

BTW, I know “listing.php” is a valid template because it shows up in the Template dropdown if I try to create a new page from WP-Admin | Pages | Add New.

Related posts

2 comments

  1. You need to specify the post_type, otherwise WordPress will default to a post (which ignores the page_template parameter).

    $my_post = array(
        'post_content'   => "My page content", 
        'post_title'     => "Page for product 1234", 
        'post_type'      => 'page', // Add this
        'page_template'  => "listing.php"
    );
    $post_id = wp_insert_post( $my_post );
    

    From the WordPress Codex:

    page_template: If post_type is ‘page’, will attempt to set the page template. On failure, the function will return either a WP_Error or 0, and stop before the final actions are called. If the post_type is not ‘page’, the parameter is ignored. You can set the page template for a non-page by calling update_post_meta() with a key of _wp_page_template.

  2. I have same problem in WP 5.5.3.
    Arg ‘post_type’ equal ‘page’ added, but wp_insert_post ignore this parameter.

    $my_post = array(
      'post_title'    => wp_strip_all_tags('Chart Manager'),
      'post_content'  => $page_content,
      'post_status'   => 'publish',
      'post_slug'     => 'chartmanager',
      'post_author'   => 1,
      'post_type'     => 'page',
      'page_template' => plugin_dir_url(__FILE__).'templates/cm_index.php'
    );
    // Insert the post into the database
    wp_insert_post( $my_post );
    

Comments are closed.