Discover in this tutorial how to display the number of posts with a specific taxonomy from a Custom Post Type (CPT) that is automatically updated using a custom shortcode.
Following a request from a subscriber (advantages of belonging to the OsomCode club ;)), I prepared a tutorial to display a dynamic number of entries using a shortcode.
This gave rise to the following question:
I imagine that using that shortcode will show all the post type courses that are on the web, right? In case we only want to show the parent courses, how would we do it?
Right now I’m showing the courses with the cover category as you showed us in another tutorial… would it be something similar?
Indeed, that strategy gives you the possibility to choose the type of post you want to show (blog entries, from Custom Post Types…), although it will always be the total number
To introduce the number of posts from a specific taxonomy (category, label…), you can use part of the “logic” of the tutorial where only one category is displayed in the home page but with a different function to make the count.
Here’s how to do it.
Instructions to generate a shortcode that display the number of entries of a category always updated
1. Create the shortcodes
Imagine you want to get the text:
Take a look at the 15 courses available.
To do this, add the following code at the end of functions.php or in your functionality plugin:
This snippet shows the number of entries of the CPT “Courses” with the category “frontpage”.
If you look at the code, you will see that it does not use the function wp_post_count () (as in the previous tutorial) but count () together with an array that indicates the taxonomy to be filtered.
This way, to get the previous sentence you would have to write:
“Take a look at the available [number_courses]”
This is just an example, but you can adapt it to your taste.
In fact, you have the same options I suggested in the tutorial to show the total number of all the entries.
2. Enter the shortcode where you want
This strategy allows you to insert the numbers anywhere on the web thanks to the shortcode.
You only have to write “[your_shortcode]” where you want it to be displayed.
- If you are using the classic editor, use the HTML tab to introduce the shortcode.
- In case you are already using the block editor you can add it to the normal paragraph block, the HTML block or the shortcode block. All of them will render the content correctly.
Now you know how to insert a number of entries from a certain category (or taxonomy) that is always kept up to date anywhere on the web using a shortcode.
All you have to do now is to put it into practice. 😉
Any questions? I read you in the comments.
And if you want to give me any suggestion for future tutorials, leave it in the contact form. Advantages of being a subscriber. 😉