WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I wanted to display top viewed posts by month, I add this code snip, to form a query and get required 15 posts, but it displays 3-4 posts.Here is my query:

global $post;

$args = array(
    'meta_key' => post_views_count,
    'orderby' => meta_value_num,
    'numberposts' => 15,
    'order' => 'DESC',

$top_viewed_posts = get_posts( $args );

foreach( $top_viewed_posts as $post ) :
    $mylimit= 30 * 86400;        //To display post for last 30 days 
    $post_age = date('U') - get_post_time('U');
    if ($post_age < $mylimit) {

        if (has_post_thumbnail()) { ?>
                <div class="widgetimg">
                    <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a>
                <span class="sidebarviews">Views: <?php echo getPostViews(get_the_ID());?></span>
endforeach; ?>

But when I remove this portion :

$mylimit= 30 * 86400;        //To display post for last 30 days 
$post_age = date('U') - get_post_time('U');
if ($post_age < $mylimit) {

It displays correctly 15 posts.

Please suggest!

share|improve this question
Can you indent your code appropriately so that it's readable? It's difficult to read in its current form. Also have you verified that you actually have 15 posts in the current month to display? – Tom J Nowell Mar 25 '13 at 15:48
I suppose you have 3/4 posts a month? In that case the code does exactly what it's supposed to do; "Order the posts by month descending by post count with a limit of 15 posts a month". – Mike Madern Mar 25 '13 at 15:49
Also, you query 15 posts, and after that, you check wich of them are from last month. – Mike Madern Mar 25 '13 at 15:54
@TomJNowell I initially had 13 posts, it used to display 2 posts then. Now, I changed that to 15, its 3 posts now – 10wtaylor Mar 25 '13 at 16:09
Then I would deem this an example of the XY problem, perhaps you should ammend your question to ask "How do I show posts from the last month" rather than "I tried to show posts in the last month, here is my solution, but my solution is also broken, give me a solution for my solution" – Tom J Nowell Mar 25 '13 at 16:29

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.