Search code examples
phpwordpresscategories

Shortcode to display WP category and subcategory ONLY if it exists


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 a 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 display fine. When the post has a different number of subcategories than 2, it gives error.

 Undefined property: WP_Error::$name in \app\public\wp-content\plugins\code-snippets\php\snippet-ops.php(582)

I know my coding skills are not great, but can I fix this shortcode and make it work?

Thanks in advance!


Solution

  • issue in your code arises because it assumes that there will always be exactly two parent categories for the current category, which is not always the case. Please try this code

    function post_parent_category_slug_shortcode() {
        // Get the current category ID
        $category_id = get_the_category(get_the_ID());
    
        // Check if the category is assigned
        if (empty($category_id)) {
            return 'No categories assigned';
        }
    
        $category = $category_id[0];
    
        // Start with the current category name
        $category_names = [$category->name];
    
        // Traverse up the category hierarchy and add parent names
        while ($category->parent != 0) {
            $category = get_category($category->parent);
    
            // Check for WP_Error before proceeding
            if (is_wp_error($category)) {
                break;
            }
    
            array_unshift($category_names, $category->name);
        }
    
        // Join the category names with a space and return
        return implode(' ', $category_names);
    }
    add_shortcode('post_parent_category_slug', 'post_parent_category_slug_shortcode');