仅显示 WP 类别和子类别(如果存在)的短代码

问题描述 投票:0回答:1

我制作了一个短代码来显示当前的帖子类别和子类别(在本例中为 2)。 当当前帖子有 2 个子类别时它工作正常,问题是当它有 1 个、超过 2 个子类别或没有子类别时。 我怎样才能让它适用于不同数量的子类别?我知道有一个“if”语句,但我无法让它发挥作用。这是我的代码:

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');

当帖子恰好有 2 个子类别时,主类别和 2 个子类别的名称显示正常。 当帖子的子类别数量少于 2 时,会出现错误。

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

我知道我的编码能力不是很好,但是有没有办法修复这个短代码并使其工作?

提前致谢!

php wordpress categories
1个回答
0
投票

代码中出现问题是因为它假设当前类别总是有两个父类别,但情况并非总是如此。请尝试这个代码

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');
© www.soinside.com 2019 - 2024. All rights reserved.