如果不存在post_title,请在插件激活上创建页面
我有一个WordPress插件,该插件正在激活时创建页面,但是我只希望它在不存在的情况下创建页面(如果插件已重新激活,则不需要重复)。
<?
function create_pages() {
if ( ! current_user_can( 'activate_plugins' ) ) return;
$pages = array(
// Donations
array(
'post_title' => 'Donations',
'post_content' => 'Give us all your money!',
),
// Cart
array(
'post_title' => 'Cart',
'post_content' => 'Buy!',
),
);
foreach($pages as $page) {
if(get_page_by_title($page['post_title']) === null):
$new_post = array(
'post_title' => $page['post_title'],
'post_content' => $page['post_content'],
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'page',
);
$post_id = wp_insert_post($new_post);
endif;
}
}
register_activation_hook(__FILE__, 'create_pages');
当我运行此内容时,没有创建页面,它似乎是由引起的,如果(get_page_by_title($ page ['post_title'])=== null):
line。如果我省略了条件,它会创建所需的页面 - 但也会重新激活它们。
我缺少什么明显的东西吗?任何帮助将不胜感激。
谢谢!
I have a WordPress plugin that is creating pages on activation, but I only want it to create the pages if they don't already exist (don't want duplicates if the plugin has been re-activated).
<?
function create_pages() {
if ( ! current_user_can( 'activate_plugins' ) ) return;
$pages = array(
// Donations
array(
'post_title' => 'Donations',
'post_content' => 'Give us all your money!',
),
// Cart
array(
'post_title' => 'Cart',
'post_content' => 'Buy!',
),
);
foreach($pages as $page) {
if(get_page_by_title($page['post_title']) === null):
$new_post = array(
'post_title' => $page['post_title'],
'post_content' => $page['post_content'],
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'page',
);
$post_id = wp_insert_post($new_post);
endif;
}
}
register_activation_hook(__FILE__, 'create_pages');
When I run this, no pages are created and it seems to be caused by the if(get_page_by_title($page['post_title']) === null):
line. If I leave that conditional out, it creates the pages needed - but also recreates them on reactivation.
Is there anything glaring I'm missing? Any help is greatly appreciated.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论