How To Count Posts Number In A Custom Post Type

Recently for a little function in my WP Coupons And Deals plugin, I needed to know how many coupons were published. Coupons are added as custom post type in my plugin.

And to my luck, I found out that WordPress already has function for that. As WordPress always does.

wp_count_posts() is the little function here.

So here’s how I used it.

‘wpcd_coupons’ is the custom post type here. You can put ‘post’, ‘page’ or any custom post type you registered.

The function returns an object with the post statuses as the properties. I didn’t want to count all posts. I just wanted to check how many published posts there were.

So on the next line, that’s what I’m doing.

To summarize, first I assigned the returned object to $coupon_count variable. Then get the number of published posts by accessing the property from the object.

Then you can do anything you want with that number.

Hope this helps.

Click Here to Leave a Comment Below

Leave a Reply: