如果不存在post_title,请在插件激活上创建页面

发布于 2025-01-24 04:49:56 字数 1099 浏览 3 评论 0原文

我有一个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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文