Shortcode to display WP category and subcategories ONLY if they exist
-
I made a shortcode to display the current post category and subcategories (2 in this case). It works fine when the current post has 2 subcategories, the problem is when it has 1, more than 2, or none. How could I make it work for different number of subcategories? I know there’s an “if” statement, but I could not make it work. This is my code:
function post_parent_category_slug_shortcode() { // get the current category ID $category_id = get_the_category(get_the_ID()); // get the current category object $child = get_category($category_id[0]->term_id); // get it's parent object $parent = get_category($child->parent); // get it's second parent object $second_parent = get_category($parent->parent); echo ($child->name . ' ' . $parent->name . ' ' . $second_parent->name); } add_shortcode( 'post_parent_category_slug', 'post_parent_category_slug_shortcode');
When the post has exactly 2 subcategories the name of the main category and 2 subcategories displays fine. When the post has a different number of subcategories than 2, it gives error. I know my coding skills are not great, but is there a way to fix this shortcode and make it work?
Thanks in advance!
Viewing 5 replies - 1 through 5 (of 5 total)
Viewing 5 replies - 1 through 5 (of 5 total)
- The topic ‘Shortcode to display WP category and subcategories ONLY if they exist’ is closed to new replies.