wp_list_categories - 自定义 post 类型

wp_list_categories - custom post types

我想显示某些 wordpress 类别,但也来自某些 post 类型 - 视频。 这只是来自默认 post 的 returns 类别的代码。

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

将 post_type 添加到查询中。 'post_type' => 'video'

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

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

此外,WordPress 中的分类法可以与 多个 post 类型相关联。 post 类型可能有 多个 分类法类型。

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

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

如果您在不同的存档页面上使用此代码,那么我们可以添加另一个函数来根据当前循环的 post 类型更改分类法名称。将此插入您的 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'
] ); ?>