0

if anyone could help it would be greatly appreciated, been trying to get this done on and off for a long time and just can't get there.

I am using the function below in a loop to count posts within a taxonomy name. Function below works fine, but would it be possible to refine the function further to only count posts that were published within the last 24 hours? I found a similar questions but couldn't get it to work with get_term_by Count posts or custom post types from last 24 hours (or from today)

Any help greatly appreciated.

<?php
global $post;
$taxonomy = "news"; 
$term_name = $post->post_title;
$term = get_term_by('name', $term_name, $taxonomy);
echo $term->count ; 
?>

1 Answer 1

3

You can create a custom WP_Query and count its result.

$wp_query = new WP_Query([
    'tax_query' => [
        [
            'taxonomy' => 'news',
            'terms' => $term_name,
            'fields' => 'name'
        ]
    ],
    'date_query' => [
        [
            'after' => '24 hours ago'
        ]
    ]
]);
$number_of_posts = $wp_query->found_posts;

Edit

I removed posts_per_page argument, as @birgire suggests, that found_posts offers total number of posts regardless of pagination.

2
  • 1
    No need to fetch so many posts, better to fetch a single post and use the found_posts property.
    – birgire
    Commented Sep 2, 2018 at 16:18
  • 1
    @birgire Thanks, I did not know, that found_posts show total result regardless of pagination! I will update my answer. Commented Sep 2, 2018 at 16:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.