获取当前帖子的wordpress中的特定类别

时间:2018-06-12 03:24:27

标签: php wordpress

我一直试图在没有运气的情况下实现以下目标。

我在wordpress中有下一个类别:

Book (level 1)
    Chapter 1 (level 2)
        Article 1 (leve 3)
        Article 2 (leve 3)
        Article 3 (leve 3)
    Chapter 2 (level 2)
        Article 1 (leve 3)
        Article 2 (leve 3)
        Article 3 (leve 3)

我的所有帖子都有3个类别,每个级别一个。我想要的只是获取当前帖子中第3级的类别并在页面的标题中使用它,但我也希望获得第2级的类别并在侧栏中使用它。

我尝试了get_the_categories()这个功能,但它向我展示了父母和孩子的所有类别,我不能只选择特定级别的一个。

我的代码是:

function proof( $atts ) {

    $categories = get_categories( array(
    'orderby' => 'name',
        'parent'  => 0,
        'hierarchical' => 0,
        'depth'     => 1
    ) );

foreach ( $categories as $category ) {
    printf( '<a href="%1$s">%2$s</a><br />',
        esc_url( get_category_link( $category->term_id ) ),
        esc_html( $category->name )
    );
}

}

add_shortcode("proof", "proof");

2 个答案:

答案 0 :(得分:0)

您可以使用以下代码检索当前类别。

   $category = get_queried_object();
   $current_cat= $category->term_id;

您可以在get_categories功能

中使用该类别ID
   $categories = get_categories( array(
    'orderby' => 'name',
    'parent'  => 0,
    'hierarchical' => 0,
    'depth'     => 1,
    'child_of' => $current_cat 
) );

答案 1 :(得分:0)

我一直在尝试使用此代码来获取父类别

///Function to get the parent category  
function parent( $atts ) {
    global $post;

    $categories = get_the_category($post->ID);

    $top_cat_obj = array();

    foreach($categories as $cat) {
        if ($cat->parent == 0) {
            $top_cat_obj[] = $cat;  
        }   
    }   

    return $top_cat_name[0]->name;
}

add_shortcode("parent", "parent");

之后,我使用了几乎相同的代码来获得该类别的孩子:

function children( $atts ) {
global $post;

$categories = get_the_category($post->ID);

//get top level category of current post
$top_cat_obj = array();

foreach($categories as $cat) {
    if ($cat->parent != 0) {
        $top_cat_obj[] = $cat;  
    }   
}   

return $top_cat_obj[0]->name;
}

add_shortcode("children", "children");
相关问题