计算来自 taxonomy.php 页面的每周(过去 7 天)帖子

Count weekly (last 7 days) posts from a taxonomy.php page

在我的分类归档页面上,我显示查询分类的术语和子术语。 我还想回应与每个子术语相关的帖子数。下面的代码工作正常,但我只想计算 recent/new 个帖子,例如。最近 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 and specifying a date_query after 属性。

/**
 * 
 * `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 ); ?>

基于@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;