Do you want to display the total number of WordPress posts for a specific custom post type you’ve created? Use the following code to get the total number of published posts in a custom post type, and then display it in your theme.
Replace “post-type-name” with the name of the custom post type you created when using the register_post_type() function. This must match exactly.
<?php // Get total number of posts in post-type-name $count_posts = wp_count_posts('post-type-name'); $total_posts = $count_posts->publish; echo $total_posts . ' custom posts. '; ?>
You can change the variable names so they are relevant to your custom post type.
Example
If your custom post type is called “Books”, your code would look like this:
<?php // Get total number of posts in "Books" post type $count_books = wp_count_posts('books'); $total_books = $count_books->publish; echo $total_books . ' books. '; ?>
The variable in the echo
statement will just return the number. You can change the word “books” to say whatever you want.
Get creative with how you use this, and share it in the comments.
Reference wp_count_posts() in the WordPress Codex.
We Recommend
https://kinsta.com › wordpress-hosting
Fast and secure infrastructure, worldwide CDN, edge caching, 35 data centers, and enterprise-level features included in all plans. Free site migrations.
https://gravityforms.com › features
Create custom web forms to capture leads, collect payments, automate your workflows, and build your business online. All without ever leaving WordPress.
Leave a Comment