已编辑:
这是一个非常简单的版本,您正在寻找做什么。你不需要WP_Query()
. 您可以使用foreach
循环和迭代器:
<?php
echo \'<ul class="job-category-list">\';
// Get the terms and order them by count in descending order.
$terms = get_terms( [
\'taxonomy\' => \'job_listing_category\',
\'orderby\' => \'count\',
\'order\' => \'DESC\',
]
);
// Set an iterator
$i = 1;
// foreach term
foreach ( $terms as $term ) {
// if the iterator is less than or equal to 12.
if ( $i <= 12 ) :
echo \'<li><a href="\' . get_term_link( $term->term_id ) . \'" title="\' . esc_attr( $term->name ) . \'">\' . $term->name . \'</a> (\' . ( $term->count ) . \')</li>\';
// Increase the iterator.
$i++;
endif;
}
echo \'<ul><!-- /job-category-list -->\';
?>
就计数而言,不知道你为什么会看到不同。但这本质上是给你想要的。
编辑:来自此wpse帖子:List taxonomy / category count showing list published posts only
您可以使用此筛选器仅获取已发布帖子的正确计数:
function get_terms_filter_published( $terms, $taxonomies, $args ) {
global $wpdb;
$taxonomy = $taxonomies[0];
if ( ! is_array($terms) && count($terms) < 1 ) {
return $terms;
}
$filtered_terms = array();
$ctr = 0;
foreach ( $terms as $term ) {
$result = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts p JOIN $wpdb->term_relationships rl ON p.ID = rl.object_id WHERE rl.term_taxonomy_id = $term->term_id AND p.post_status = \'publish\' LIMIT 1");
$published_terms[ $ctr ] = $term;
if ( intval($result) > 0 ) {
$published_terms[ $ctr ] = $term;
} else {
// you can comment this out if you don\'t want to show empty terms
$published_terms[ $ctr ]->count = 0;
}
$ctr++;
}
return $published_terms;
}
add_filter(\'get_terms\', \'get_terms_filter_published\', 10, 3);
因此,将该过滤器函数添加到函数中。php并使用上面的代码来获取您想要的内容-根据帖子数量,仅前12个类别。