WordPress Development Asked by Northtime on November 11, 2021
I’d like to create a shortcode that would display the post count for a specific category within a custom post type. I’ve been trying to alter the code below but need some help. Could anyone let me know how to tweak so that the shortcode is for a specific custom post type.
// Add Shortcode to show posts count inside a category function category_post_count( $atts ) { $atts = shortcode_atts( array( 'category' => null ), $atts ); // get the category by slug. $term = get_term_by( 'slug', $atts['category'], 'category'); return ( isset( $term->count ) ) ? $term->count : 0; } add_shortcode( 'category_post_count', 'category_post_count' );
Thanks in advance!
If for some reason you're using the shortcode inside the loop, you could try the code below. Failing that, your best bet is to get to grips with WP_Query as suggested in another answer.
Add to functions.php
function category_post_count( $atts ) {
$atts = shortcode_atts( array(
'category' => null,
'type' => null
), $atts );
$term = get_term_by( 'slug', $atts['category'], 'category');
$tpt = $atts['type'];
if( get_post_type() == $tpt ) {
return $term->count;
}
}
add_shortcode( 'category_post_count', 'category_post_count' );
Typical usage
[category_post_count category="category_slug" type="post_type"]
Answered by Nikki Mather on November 11, 2021
I think you would be better off using get_posts
or a new WP_Query
instead of get_term_by
. That would allow you to get posts for your custom post type, and then filter by taxonomy/term name.
If you're comfortable enough with WP Query you could try something like this: Query posts by taxonomy term name
Answered by Charlie Stanard on November 11, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP