wordpress - 页面不使用提供给 wp_insert_post() 的模板

标签 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"; 

我尝试在数组中使页面使用“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: 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.

关于wordpress - 页面不使用提供给 wp_insert_post() 的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34844363/

相关文章:

php - 自定义 SQL 从类别数组中获取帖子,并从排除的类别中返回 id。怎么了?

php - 检测何时在 Woocommerce 中单击 "remove"优惠券按钮

javascript - 如何在 WordPress 管理控制面板中运行 Javascript?

php - 如何在 Underscores Wordpress 主题中创建第二个侧边栏?

wordpress - 我可以在 Wordpress wp_nav_menu() 中的 anchor 标记后添加分隔符 <li> 吗?

jquery - 移动设备上的 Wordpress 下拉故障

jquery - 将 jQuery Validate 插件与 TinyMCE 编辑器结合使用

php - 获取类别 wordpress 中的标签 - 可过滤的投资组合

php - Wordpress Divi - 如何更改移动标题以具有按钮

php - 在 WordPress 的钩子(Hook)之间传递变量