TrinhQuangTruong
TrinhQuangTruong

Reputation: 105

Wordpress how to change post status from pending to approved

I need to change post status from pending to approved when create a new post and if author has a approved post before.

I have a function like this but the code doesn't work at all.

Please help:

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;
}

Upvotes: 0

Views: 1784

Answers (1)

Ruvee
Ruvee

Reputation: 9109

the code doesn't work at all

Because

  • wp_insert_post is an action hook not a filter hook. Therefore, using add_filter is incorrect.
  • You asked wp_insert_post to give you two arguments, but you used one in your callback function.
  • $data is the post object, it's not an array. You can NOT use it like $data['post_type'].
  • 'post_status' => 'approved' does NOT exist. See the list of valid post statusesDocs
  • What you're looking for is post status publish NOT approved.

The following code goes in the functions.php file of your theme.

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
    ));
  }
}

The conditions that i used in order for a post to be published automatically:

  • The post_type should be 'post'
  • AND
  • The author must already have at least one published post.
  • AND
  • The post_status should NOT be publish already.
  • AND
  • The post_status should NOT be trash either.

It's also worth mentioning that I used WP_Query and its property found_posts instead of using get_posts and count to figure out whether an author has already published a post or not.


This answer has been fully tested on wordpress 5.8.1 and works.

Upvotes: 4

Related Questions