首页 > 解决方案 > 统计来自 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>';
}

标签: wordpresspostcounttaxonomytaxonomy-terms

解决方案


我们可以创建一个自定义函数,查询我们当前的分类术语并指定一个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 ); ?>

推荐阅读