问题描述
在我的分类存档页面上,我显示了查询分类的术语和子术语。 我还想回应与每个子术语相关的帖子数量。下面的代码工作正常,但我只想计算最近/新的帖子,例如。在过去 7 天内发布。
是否可以通过任何方式过滤 $term->count
来实现此目的?
$taxonomy = get_query_var('taxonomy');
// get main terms
$terms = get_terms( $taxonomy,array( 'orderby' => 'name' )
);
// display terms
foreach ( $terms as $term ) {
echo '<h2 class="text-center">' . $term->name . '</h2>';
// display term children as list
$term_id = $term->term_id;
$child_terms = get_term_children( $term_id,$taxonomy );
echo '<ul class="lesson-categories">';
foreach ( $child_terms as $child_term ) {
$term = get_term_by( 'id',$child_term,$taxonomy );
echo '<li>';
echo $term->name;
// SHOW POST COUNT
echo $term->count;
echo '</li>';
}
echo '</ul>';
}
解决方法
我们可以创建一个自定义函数,查询当前的 taxonomy term 并指定一个 date_query
after
属性。
/**
* https://stackoverflow.com/a/66780352/3645650
* `get_posts_tally_weekly( $post_type = 'post',$post_status = 'any',$taxonomy = 'category',$term = 'uncategorized' );`
* @return Integer Return a weekly posts tally.
* @param String $post_type (Optional) Post type to query. Default to 'post'.
* @param String $post_status (Optional) Post status to query. Default to 'any'.
* @param String $taxonomy (Optional) Taxonomy to query. Default to ''.
* @param String $term (Optional) Term to query. Default to ''.
*/
function get_posts_tally_weekly( $post_type = 'post',$term = 'uncategorized' ) {
$query = new WP_Query( [
'post_type' => $post_type,'post_status' => $post_status,'orderby' => 'date','order' => 'DESC',$taxonomy => $term,'date_query' => [
'after' => '1 week ago'
],] );
return $query->found_posts;
wp_reset_postdata();
};
在前端,我们可以调用我们的自定义函数 get_posts_tally_weekly()
。我们可以指定 $post_type
、$post_status
、$taxonomy
和 $term
。
从分类页面,检索每周帖子数:
<?= get_posts_tally_weekly( 'custom-post-type-slug','publish',get_queried_object()->taxonomy,get_queried_object()->slug ); ?>
,
基于答案的@amarinediary 解决方案。
带有 date_query
的新 WP_Query 成功了:
// SHOW POST COUNT
$post_args = array(
'post_type' => 'guided_lessons','tax_query' => array(
array(
'taxonomy' => $taxonomy,'field' => 'id','terms' => $child_term,),// Checking for the date here
'date_query' => array(
array(
'after' => '1 week ago',);
$post_query = new WP_Query( $post_args );
$new_posts = $post_query->found_posts;
echo $new_posts;