12% off of LTD using this coupon: TWELVEPERCENTOFF. Promo ends on 2 Dec midnight UTC.
Published on Sep 6, 2021

Get Post Count for a Given Post Type in WordPress

Sridhar Katakam

Here’s a simple function that can be used to get the number of published posts in a specified post type:

function wpdd_posts_count_for( $post_type ) {
	return wp_count_posts( $post_type )->publish;
}

It can be added in child theme’s functions.php or a plugin like Code Snippets.

Sample usage:

<?php 

echo wpdd_posts_count_for( 'post' );

?>

Practical Example

Let’s say you want to add a counter that counts from 0 up to the total number of published items of a podcast CPT in Oxygen when using OxyExtrasCounter component.

With the above function defined, you would click “data” for the “End Digit” input field, click “PHP Function Return value” and

Function Name: wpdd_posts_count_for
Function Arguments: podcast

and click INSERT

to have the end digit be dynamic and always (warning: caching may affect) automatically reflecting the number of published entries of your specified post type.

Reference

https://wordpress.stackexchange.com/a/26569/14380

tagschevron-leftchevron-rightchainangle-rightangle-upangle-downfolder-omagnifiercrossmenuchevron-downarrow-right