页面未使用提供给 wp_insert_post() 的模板

Ste*_*eve 2 wordpress

我用下面的代码创建了一个新页面:

$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"; 
Run Code Online (Sandbox Code Playgroud)

我尝试在数组中使页面使用“listing.php”作为模板,但是当我将http://example.com/?p=61放入浏览器地址栏中时,上面$post_id返回的61 是wp_insert_post()页面找到了,但它使用“single.php”作为模板。

为什么不使用“listing.php”,我怎样才能让它使用“listing.php”?

顺便说一句,我知道“listing.php”是一个有效的模板,因为如果我尝试从 WP-Admin 创建一个新页面,它会显示在模板下拉列表中 | 页面 | 添新。

Kir*_*ard 5

您需要指定post_type,否则 WordPress 将默认为一个帖子(忽略该page_template参数)。

$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 );
Run Code Online (Sandbox Code Playgroud)

来自Wordpress 法典

page_template:如果post_type是'page',将尝试设置页面模板。失败时,该函数将返回 WP_Error 或 0,并在调用最终操作之前停止。如果 post_type 不是 'page',则忽略该参数。您可以通过调用update_post_meta()键为非页面设置页面模板_wp_page_template