列出当前分类档案的类别

List categories of current taxonomy archive

Here's my site: http://bmi.brownsmedicalimaging.com/product-category/c-arm/

我创建了一个名为 Products 的自定义 post 类型。然后我创建了 2 个自定义分类法,CategoriesManufacturers。例如,如果我正在查看上面的“C 型臂”类别页面,我会显示该类别中的 2 post。我怎样才能让它显示该类别的制造商列表?现在它只输出我定义的所有制造商。这是我的代码:

add_shortcode( 'my_cat_list', 'my_list_categories_shortcode' );
/**
 * this function outputs your category list where you
 * use the [my_cat_list] shortcode.
 */
function my_list_categories_shortcode() {
    $args = array( 
        'echo' =>   false,
        'taxonomy'   =>     'product-manufacturer',
        'title_li' => '',
    );
    return wp_list_categories( $args ); 
}

所以一般来说,这不是一件大事,但我们应该避免对数据库进行不必要的调用,而 WordPress 本身并没有为我们提供这样的功能。因此,出于性能原因,我创建了自己的自定义 sql 查询。参见:

function get_related_list_categories ($term_taxonomy_id, $related_taxonomy)
{
    global $wpdb;

    $sql = "SELECT DISTINCT(term_taxonomy_id)
            FROM {$wpdb->prefix}term_relationships
            WHERE object_id IN (
                SELECT DISTINCT(p.ID)
                FROM {$wpdb->prefix}posts AS p LEFT JOIN {$wpdb->prefix}term_relationships AS tr ON (p.ID = tr.object_id)
                WHERE tr.term_taxonomy_id IN ({$term_taxonomy_id}) AND p.post_type = '{$post_type}' AND (p.post_status = 'publish')
              ) AND term_taxonomy_id IN (
                  SELECT term_id FROM {$wpdb->prefix}term_taxonomy WHERE taxonomy = '{$related_taxonomy}'
              )";

    if (empty($term_ids = $wpdb->get_col($sql))) {
        return FALSE;
    }

    return $wp_list_categories(['include' => $term_ids, 'taxonomy' => $related_taxonomy, 'echo' => false, 'title_li' => '',]);
}

get_related_list_categories($product_category_id, 'product-manufacturer');

同样,我选择 product_category_id 作为第一个参数(与 slug 相对),因为我认为您很可能拥有它并且不需要调用数据库来获取 slug .无论哪种方式,您都可以根据自己的喜好自定义功能。我相信您会有自己的调整,例如我 return false on no term found,但您可能想以其他方式进行调整。如果这对您有用,或者您有任何疑问,请告诉我。


更新:如果调试需要进一步解释。

sql 查询由两个子查询组成。

SELECT DISTINCT(p.ID)
FROM {$wpdb->prefix}_posts as p
    LEFT JOIN {$wpdb->prefix}_term_relationships as tr ON (p.ID = tr.object_id)
WHERE tr.term_taxonomy_id IN ({$term_taxonomy_id})
    AND p.post_type = '{$post_type}'
    AND (p.post_status = 'publish')
  1. 这会找到与当前相关术语关联的所有 post。它应该与该存档页面的 post id 相匹配。 运行 此查询单独进行测试以查看是否返回了正确的 post ID。如果你想为多个术语或 slug 等做,你可以调整 WHERE 子句。
SELECT term_id
FROM {$wpdb->prefix}_term_taxonomy
WHERE taxonomy = 'related_experience'
  1. 第二个子查询获取 'related_experience' 分类法(或您想要的任何二级分类法)的所有术语。您应该 运行 这并验证 'related_experience' 的所有术语 ID 都回来了

然后父 sql 查询加入第一个分类中的 post id,并从第二个分类中获取所有术语,这些术语也显示在具有以下特征的 post 中第一个分类法。