0

I want to limit Page creation to be 3, without interfering other post type like Post. I'm using below function:

  function set_post_to_draft_page_only( $data, $postarr ) {
    if($data['post_type'] == 'page') {

      if( wp_count_posts('page')->publish > 2 ) {
        $data['post_status'] = 'draft';
      }
      return $data;
    }
  }
  add_filter( 'wp_insert_post_data', 'set_post_to_draft_page_only', 99, 2 );

The function above works for Page but it will interfere Post (Add New Post will show error). So I added return $data; to exclude Post:

  function set_post_to_draft_page_only( $data, $postarr ) {
    if($data['post_type'] == 'page') {

      if( wp_count_posts('page')->publish > 2 ) {
        $data['post_status'] = 'draft';
      }
      return $data;
    }
    if($data['post_type'] == 'post') {          // without this part, Add New Post will show error
      return $data;
    }
  }
  add_filter( 'wp_insert_post_data', 'set_post_to_draft_page_only', 99, 2 );

This is not good way because if I added more post type, I need to manually add more exception.

So what is the better way to only limit Page creation without interfering other post type?

1 Answer 1

2

I would suggest one slight change to your logic as follows:

function set_post_to_draft_page_only( $data, $postarr ) {
    if($data['post_type'] == 'page') {

      if( wp_count_posts('page')->publish > 2 ) {
        $data['post_status'] = 'draft';
      }
    }
    return $data;
  }
  add_filter( 'wp_insert_post_data', 'set_post_to_draft_page_only', 99, 2 );

You were not returning $data if post type was anything other than 'page'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.