1

I am using this code to count number of posts for one custom post type.

What's the best way to change this to sum up together 3 different custom post types?

function get_all_them_ven_posts(){
    $post_type = 'restaurants';
    $count_posts = wp_count_posts( $post_type );

    $published_posts = $count_posts->publish;
    return $published_posts;
}

3 Answers 3

2

Why not just get the count for each post type and sum them?

function get_all_them_ven_posts(){
  $count= 0;
  $post_types = [ 'postType1', 'postType2', 'postType3' ];
  foreach( $post_types as $post_type ) {
    $count_posts =  wp_count_posts( $post_type );
    $count = $count + $count_posts->publish;
  }
  return $count;
}
0

I was curious, so I microtimed it with three post types and about 120 posts shared across them. Comparing three wp_count_posts() calls with one get_posts() call. If you make use of the fields parameter of the latter, with the value ids, then they are about the same speed, otherwise it is 30 times slower. The get_posts() method is possibly in the 95% rang in comparison, so it might be a little bit faster, but I didn't run nearly enough iterations to have a conclusive result. So I would say you can do it either way.

// use either
$p1c = wp_count_posts( 'post-type-1' )->publish;
$p2c = wp_count_posts( 'post-type-2' )->publish;
$p3c = wp_count_posts( 'post-type-3' )->publish;
$res = $p1c + $p2c + $p3c;
//alternatively
$pts = [ 'product', 'post', 'page' ];
$res = 0;
foreach ( $pts as $pt) {
    $res = $res + wp_count_posts( $pt )->publish;
}

// or use this
$res = count( get_posts( [ 
  'post_type' => [ 'product', 'post', 'page' ], 
  'posts_per_page' => -1, 
  'fields' => 'ids' 
] ) );
0

Get total number of post in custom post type

$args = array( 'post_type' => 'custompost', 'post_status' => 'publish', 'posts_per_page' => -1);
$loop = new WP_Query( $args );
$total = $loop->found_posts;
echo $total;
1
  • Use 'fields' => 'ids' otherwise the performance is bad. Commented Feb 28, 2018 at 12:27

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.