⚡Voxel Black Friday Sale is now Live

Show How Many Categories are Assigned to Post

Description/Instructions

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”.

If this snippet helped, feel free to buy me a taco :)

Instructions

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
Copy Code

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
Copy Code

Let's Chat About this Snippet