Snippets / HTML
HTML
PHP
Show How Many Categories are Assigned to Post
D
Donald McGuinn
·
325 views
·
Updated 2 years ago
This will allow you to show how many more taxonomies are assigned to the post to signify there are more for the user to see. It will take the total categories, subtract 1, and out it as +"number".
These are the two shortcodes you can use
This allows you to choose the post type, taxonomy, and the post ID
[dynamic_count post_type="product" taxonomy="product_cat" id="123"]
This is for you to put on the preview card or single post type. Change it how you need it.
[dynamic_count post_type="product" taxonomy="product_cat"]
HTML · 5 lines
function custom_dynamic_count_shortcode($atts) {
// Shortcode attributes allowing 'post_type' and 'taxonomy' to be specified
$atts = shortcode_atts(
array(
'post_type' => 'post', // Default post type
'taxonomy' => 'category', // Default taxonomy
'id' => null, // Default to null, allowing current post ID to be used if not specified
),
$atts,
'dynamic_count'
);
// Use specified ID or fallback to global post ID
$post_id = !empty($atts['id']) ? $atts['id'] : get_the_ID();
// Ensure we have a valid post ID
if ($post_id) {
// Retrieve terms from the specified taxonomy for the given post ID
$terms = wp_get_post_terms($post_id, $atts['taxonomy'], array("fields" => "ids"));
// Count the terms and subtract 1
$term_count = count($terms) - 1;
// Check if adjusted terms count is 0 or less
if ($term_count > 0) {
return "+" . $term_count;
}
}
return ""; // Return empty string if conditions aren't met or if adjusted count is 0 or less
}
// Register the shortcode with WordPress
add_shortcode('dynamic_count', 'custom_dynamic_count_shortcode');
PHP · 34 lines
Discussion 2
Ask a question or share how you used this.
Log in
to join the discussion.
imfaisal024
2 years ago
I tried on Product Taxonomies it's not working can you please help to fix
Donald McGuinn
2 years ago
Make sure all the attributes are correct. I havent tried with product but im sure it works the same.