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.
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.
You need to specify the
post_type
, otherwise WordPress will default to a post (which ignores thepage_template
parameter).From the WordPress Codex:
I have same problem in WP 5.5.3.
Arg ‘post_type’ equal ‘page’ added, but wp_insert_post ignore this parameter.