wordpress - 统计来自 taxonomy.php 页面的每周(过去 7 天)帖子
问题描述
在我的分类存档页面上,我显示了查询分类的术语和子术语。我还想回应与每个子术语相关的帖子数量。下面的代码工作正常,但我只想计算最近/新的帖子,例如。在过去 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>';
}
解决方案
我们可以创建一个自定义函数,查询我们当前的分类术语并指定一个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', $post_status = 'any', $taxonomy = 'category', $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 ); ?>
推荐阅读
- django - Filtering based on a foreign key in Django
- swift - 在不破坏撤消堆栈的情况下在 NSTextView 中附加文本
- python - Python类分层继承查询
- java - Android NotificationManager 不提醒用户
- python - Player does not stop at bottom edge of screen when using gravity in pygame tutorial
- gatsby - How to add local script file to gatsby
- r - R包学习器中有关“不可见”的消息
- authentication - 如何验证 WebSocket 连接
- bluetooth - 是否有针对 Debian 10 中 BlueZ 蓝牙(版本 5.50)的零星 SIGSEGV 崩溃的错误修复?
- java - Spring Boot:基本身份验证返回 401,但在 Postman 中工作