I was curious, so I microtime
d it with three post types and about 120 posts shared across them. Comparing three wp_count_posts()
calls with one get_posts()
, because the latter was mentioned on the developer page of the former as alternative approach 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. Possibly theThe get_posts()
method is speed-wisepossibly in the .9 to .9595% 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' ],
'numberposts''posts_per_page' => -1,
'fields' => 'ids'
] ) );