php - WP 仅显示包含该帖子类型的帖子的类别

标签 php wordpress

在 WordPress 中,我创建了 2 个自定义帖子类型 Services & Work它可以使用 wp 默认类别和标签分类法。

在任何给定的单个帖子页面上,我需要列出该帖子类型可用的类别。

我尝试过使用 $args = array( 'hide_empty' => 1, 'taxonomy' => 'category' ); wp_list_categories( $args ); 仅列出与帖子关联的类别,但该列表不考虑帖子类型。

如何仅列出该帖子类型使用的类别?

最佳答案

问题已回答here :

Put the following in your functions.php:

function wp_list_categories_for_post_type($post_type, $args = '') {
    $exclude = array();

    // Check ALL categories for posts of given post type
    foreach (get_categories() as $category) {
        $posts = get_posts(array('post_type' => $post_type, 'category' => $category->cat_ID));

        // If no posts found, ...
        if (empty($posts))
            // ...add category to exclude list
            $exclude[] = $category->cat_ID;
    }

    // Set up args
    if (! empty($exclude)) {
        $args .= ('' === $args) ? '' : '&';
        $args .= 'exclude='.implode(',', $exclude);
    }

    // List categories
    wp_list_categories($args);
}

Now you can call wp_list_categories_for_post_type('photos'); or wp_list_categories_for_post_type('videos', 'order=DESC&title_li=Cats'); and the like.

关于php - WP 仅显示包含该帖子类型的帖子的类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40369853/

相关文章:

php - 数据库存在,但 WordPress 无法建立数据库连接

html - 去除页面顶部的白条 - Wordpress theme Lounge

mysql - 在 mysql 中复制 wordpress 密码哈希

PHP MySQL JSON 输出

php - 插入函数时出现mysql版本错误

php - PHP x MYSQL 使用 UTF8_encode() 和 UTF8_decode() 时出现重音错误?

php - 在 Linux 上本地运行初始设置后的 WordPress "Notice: Undefined index: host"

PHP声明编码

php - Admin-ajax.php 302 错误 WordPress

wordpress - 图像随机半损坏