从共享的自定义分类中排除自定义邮政类型

时间:2014-07-31 作者:ngearing

我有一些自定义帖子类型,其中两个共享自定义分类法。

有没有办法只列出一种自定义帖子类型的分类术语?

目前,我可以得到一个术语列表,并按照我的意愿显示它们,但这是两种自定义帖子类型的混合。我需要一种方法来过滤掉其他类型的帖子。

这是我的侧边栏中的内容。php:

<?php
    $post_type = get_post_type();

    if($post_type == \'artists\' || $post_type == \'educations\') {
        $taxonomy = \'art_categories\'; // Sharing same taxonomy
    } else {
        $taxonomy = $post_type.\'_categories\'; // Other post type taxonomy
    }

    $term = get_term_by("slug", get_query_var($taxonomy), $taxonomy);

    $children = get_term_children($term->term_id, $taxonomy);


    if(empty($children)) { // Cats with NO kids

        $parent = $term->parent;

    } elseif($term->term_id > 0) { // Cats with kids

        $parent = $term->term_id;

    } else { // TOP Level Cats

        $parent = 0;

    }   

    $args = array(
        "type" => $post_type,
        "taxonomy" => $taxonomy,
        "parent" => $parent,
        "exclude" => 2,
    );

    $categories = get_categories($args);


    if($categories) {

        echo "<ul>";

        foreach($categories as $cat) {

            echo "<li class=\'cat-item\'>";

                echo "<a href=\'" . get_term_link($cat) . "\'>" , $cat->name , "</a>";

            echo "</li>";

        }

        echo "</ul>";

    }

?>

1 个回复
最合适的回答,由SO网友:bonger 整理而成

您可以尝试使用terms_clauses 滤器

function wpse156370_terms_clauses( $pieces, $taxonomies, $args ) {
    global $wpdb;
    $pieces[\'fields\'] .= $wpdb->prepare( \', (SELECT COUNT(*) FROM \'
        . $wpdb->posts . \' p, \' . $wpdb->term_relationships . \' p_tr\'
        . \' WHERE p_tr.object_id = p.ID AND p_tr.term_taxonomy_id = tt.term_taxonomy_id\'
        . \' AND p.post_status = %s AND p.post_type = %s) AS post_count\', \'publish\', $args[\'type\'] );
    $pieces[\'orderby\'] = \' HAVING post_count > 0 \' . $pieces[\'orderby\'];
    return $pieces;
}
然后在get_categories

    add_filter( \'terms_clauses\', \'wpse156370_terms_clauses\', 10, 3 );
    $categories = get_categories( $args );
    remove_filter( \'terms_clauses\', \'wpse156370_terms_clauses\', 10, 3 );
这是一种黑客行为,滥用拥有(和$pieces[\'orderby\']) as不能引用WHERE中的post\\u count别名,但。。。似乎有效。

要获取要区分的术语链接,请为每个术语添加一个查询变量,例如

echo "<a href=\'" . add_query_arg( \'post_type\', $post_type, get_term_link($cat) ) . "\'>" , $cat->name , "</a>";
然后在pre_get_posts 行动

function wpse156370_pre_get_posts($query) {
    $taxonomy = \'art_categories\';
    $post_types = array( \'artists\', \'educations\' );
    if ($query->is_main_query() && $query->is_tax( $taxonomy ) && ( $post_type = get_query_var( \'post_type\' ) ) && in_array( $post_type, $post_types ) ) {
        $query->set( \'post_type\', $post_type );
    }
}
add_action( \'pre_get_posts\', \'wpse156370_pre_get_posts\' );

结束