我使用以下代码创建了一个新页面:
$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";
我尝试在数组中使页面使用“listing.php”作为模板,但是当我输入 http://example.com/?p=61 时进入我的浏览器地址栏,其中 61 是上面的 wp_insert_post()
返回的 $post_id
,可以找到该页面,但它使用“single.php”作为模板。
为什么它不使用“listing.php”,如何让它使用“listing.php”?
顺便说一句,我知道“listing.php”是一个有效的模板,因为如果我尝试从 WP-Admin | 创建一个新页面,它会显示在模板下拉列表中。页数 |添加新内容。
最佳答案
您需要指定 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 );
来自Wordpress Codex :
page_template:
Ifpost_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 callingupdate_post_meta()
with a key of_wp_page_template
.
关于wordpress - 页面不使用提供给 wp_insert_post() 的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34844363/