duanbaque4230 2018-06-12 03:24
浏览 37

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

I have been trying to achieve the following without luck.

I have the next categories in 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)

All my posts has 3 categories, one for each level. What I want is get just the category on level 3 in the current post and use it in the header of my page, but also I want get the category on level 2 and use it in the sidebar.

I have tried the function get_the_categories(), but it show me all the categories parents and childs and I cannot choose just one in a specific level.

My code is this:

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条回答 默认 最新

  • dsw7547 2018-06-13 04:41
    关注

    You can retrieve the current category using following code.

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

    and you can use that category id in your get_categories function

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

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大