【问题标题】:Wordpress how to change post status from pending to approvedWordpress 如何将帖子状态从待处理更改为已批准
【发布时间】:2021-10-15 13:58:21
【问题描述】:

我需要在创建新帖子时将帖子状态从 pending 更改为 approved,如果作者之前有批准的帖子。

我有这样的功能,但代码根本不起作用。

请帮忙:

add_filter('wp_insert_post', 'change_post_status_when_insert_post_data',10,2);

function change_post_status_when_insert_post_data($data) {
    if($data['post_type'] == "post") {
      $posts_args = array(
        'author__in' => $id,
        'post_type' => 'post',
        'post_status' => 'approved',
        'posts_per_page'  => -1,
      );
      $user_posts = get_posts($posts_args);
      $count = count($user_posts);
      if($count > 0) {
        $data['post_status'] = 'approved';
      } else {
        $data['post_status'] = 'pending';
      }
    }
  return $data;
}

【问题讨论】:

    标签: php wordpress wordpress-theming hook


    【解决方案1】:

    代码根本不起作用

    因为

    • wp_insert_post 是一个动作钩子而不是过滤器钩子。因此,使用add_filter 是不正确的。
    • 您要求wp_insert_post 给您两个参数,但您在回调函数中使用了一个。
    • $data 是帖子object,它不是array。你不能像$data['post_type']那样使用它。
    • 'post_status' => 'approved' 不存在。 See the list of valid post statusesDocs
    • 您要查找的是帖子状态 publish 而不是 approved

    以下代码位于您主题的functions.php 文件中。

    add_action('wp_insert_post', 'change_post_status_when_insert_post_data', 999, 2);
    
    function change_post_status_when_insert_post_data($post_id, $post)
    {
    
      $posts_args = array(
        'posts_per_page'  => -1,
        'author'          => $post->post_author,
        'post_status'     => 'publish',
      );
    
      $user_posts = new WP_Query($posts_args);
    
      $post_status = (('post' == $post->post_type) && ($user_posts->found_posts) && ('publish' != $post->post_status) && ('trash' != $post->post_status)) ? 'publish' : 'pending';
    
      if ('publish' == $post_status) {
        wp_update_post(array(
          'ID'            =>  $post_id,
          'post_status'   =>  $post_status
        ));
      }
    }
    

    我为自动发布帖子而使用的条件:

    • post_type 应该是“帖子”
    • 作者必须已经至少发表过一篇文章。
    • post_status 不应该是 publish
    • post_status 也不应该是 trash

    还值得一提的是,我使用WP_Query 及其属性found_posts 而不是使用get_postscount 来确定作者是否已经发布了帖子。


    此答案已在 wordpress 5.8.1 上经过全面测试并且有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-14
      • 1970-01-01
      • 1970-01-01
      • 2013-03-28
      相关资源
      最近更新 更多