[英]WordPress get_terms() function not display custom taxonomy categories for woocommerce
[英]Wordpress - taxonomy used on multiple post types - how to get_terms / get_categories for just one?
我已經為多種帖子類型注冊了分類法,認為這是設置網站的最佳方式,而不是重復使用相同的分類法。
但是,現在我遇到了一個問題,我需要列出一個帖子類型的已使用的分類法,但是它列出了所有這兩種類型的列表分類法。 我該如何解決這個問題? Niether get_categories或get_terms似乎可以選擇指定要為其分類的郵政類型。
編輯注意:每種帖子類型也有多個分類
有人可以幫忙嗎?
register_taxonomy(
'sectors',
array('case-study', 'resource'), //used in multiple post types
[
'labels' => [
'name' => __( 'Sectors' ),
'singular_name' => __( 'Sector' ),
],
'hierarchical' => true,
'show_admin_column' => true,
]
);
$sectors = get_categories( array('taxonomy' => 'sectors') ); //prints out selected taxonomies for both case studies and resources when I want just resources.
$services = get_categories( array('taxonomy' => 'services') );
試試這個
<?php
$custom_terms = get_terms('custom_taxonomy_name');
foreach($custom_terms as $custom_term) {
wp_reset_query();
$args = array('post_type' => 'custom_post_type_name',
'tax_query' => array(
array(
'taxonomy' => 'custom_taxonomy_name',
'field' => 'slug',
'terms' => $custom_term->slug,
),
),
);
$loop = new WP_Query($args);
if($loop->have_posts()) {
echo '<h2>'.$custom_term->name.'</h2>';
while($loop->have_posts()) : $loop->the_post();
echo '<a href="'.get_permalink().'">'.get_the_title().'</a><br>';
endwhile;
}
}
?>
我發現下面的代碼有點像魅力:)
function df_terms_clauses( $clauses, $taxonomy, $args ) {
if ( isset( $args['post_type'] ) && ! empty( $args['post_type'] ) && $args['fields'] !== 'count' ) {
global $wpdb;
$post_types = array();
if ( is_array( $args['post_type'] ) ) {
foreach ( $args['post_type'] as $cpt ) {
$post_types[] = "'" . $cpt . "'";
}
} else {
$post_types[] = "'" . $args['post_type'] . "'";
}
if ( ! empty( $post_types ) ) {
$clauses['fields'] = 'DISTINCT ' . str_replace( 'tt.*', 'tt.term_taxonomy_id, tt.taxonomy, tt.description, tt.parent', $clauses['fields'] ) . ', COUNT(p.post_type) AS count';
$clauses['join'] .= ' LEFT JOIN ' . $wpdb->term_relationships . ' AS r ON r.term_taxonomy_id = tt.term_taxonomy_id LEFT JOIN ' . $wpdb->posts . ' AS p ON p.ID = r.object_id';
$clauses['where'] .= ' AND (p.post_type IN (' . implode( ',', $post_types ) . ') OR p.post_type IS NULL)';
$clauses['orderby'] = 'GROUP BY t.term_id ' . $clauses['orderby'];
//print_r( $clauses );
}
}
return $clauses;
}
add_filter( 'terms_clauses', 'df_terms_clauses', 10, 3 );
$terms = get_terms( 'animal_cat', array(
'orderby' => 'count',
'hide_empty' => 0
) );
foreach( $terms as $term ) {
// Define the query
$args = array(
'post_type' => 'animal',
'animal_cat' => $term->slug
);
$query = new WP_Query( $args );
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.