首页 > 解决方案 > wp_list_categories - 自定义帖子类型

问题描述

我想显示某些 wordpress 类别,但也来自某些帖子类型 - 视频。那是代码只返回默认帖子的类别。

function my_vc_shortcode( $atts ) {
return '
    <ul class="categories">
         '.wp_list_categories( array(
            'orderby' => 'name',
            //'post_type' => 'video', 
            'include' => array(20216, 20375, 20216),
            'title_li' => '',
        ) ).'
    </ul>
    ';
}
add_shortcode( 'my_vc_php_output', 'my_vc_shortcode');

标签: wordpresswp-list-categories

解决方案


wp_list_categories()函数没有post_type参数。检查法典https://developer.wordpress.org/reference/functions/wp_list_categories/

此外,WordPress 中的分类法可以与多个帖子类型相关联。并且一个帖子类型可能有多个分类类型。

但是,有一个taxonomy参数可以用于wp_list_categories()函数。像这样的东西:

wp_list_categories( array(
    'orderby' => 'name',
    'taxonomy' => 'video_category' // taxonomy name
) )

如果您在不同的存档页面上使用此代码,那么我们可以添加另一个函数来根据当前循环的帖子类型更改分类名称。将其插入您的functions.php

function get_post_type_taxonomy_name(){
    if( get_post_type() == 'some_post_type' ){ // post type name
        return 'some_post_type_category'; // taxonomy name
    } elseif( get_post_type() == 'some_another_post_type' ){ // post type name
        return 'some_another_post_type_category'; // taxonomy name
    } else {
        return 'category'; // default taxonomy
    }
}

这在您的模板文件中:

<?php echo wp_list_categories( [
    'taxonomy'  => get_post_type_taxonomy_name(),
    'orderby' => 'name'
] ); ?>

推荐阅读