Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm going nuts.

All I have is a simple loop on the home page of the site (which is a static page), and it should show the most recent (1) post of a certain category. The trouble is no matter what i do, it seems including category parameter makes sorting by date not work.

This is the loop I am using:

<?php
    $announcements = new WP_Query();
    $announcements->query('showposts=1&cat=4');
    while ( $announcements->have_posts() ) : $announcements->the_post();
?>

The oldest post always shows up when using this. I have tried adding &orderby=date and &order=DESC, but nothing works until I remove the &cat=4, at which point things are sorted by date just fine.

Am I missing something, or is sorting a single category by date not possible?

share|improve this question
    
Is 4 a custom taxonomy? –  vancoder Mar 22 '13 at 18:59
    
Nope, just regular old posts. –  Gabriel Mar 22 '13 at 19:09
1  
Hmm, your code works fine for me. Are you sure you have more than one post in category 4? –  vancoder Mar 22 '13 at 19:17
    
I'd tend to agree with @vancoder, you may only have 1 post in category 4. Try removing that and adding &orderby=date&order=DESC. Does it work then? –  Pat Mar 22 '13 at 19:29
    
I definitely have more posts than 1 in that category. Removing the &cat=4 causes date sorting to work normally, but obviously shows all posts. –  Gabriel Mar 22 '13 at 19:46
show 1 more comment

1 Answer 1

If it doesn't work, chances are you do not have at least one post linked to that specific category 4.

If you wanted to sort by DESC and by date, you wouldn't have to specify those as arguments in the query because those are both the defaults for sorting.

Also, instead of initializing a WP_Query object and simply using the query method, try to get in the habit of passing an array of arguments to the constructor.

So in your case, try the following:

$args = array('cat' => 4, 'posts_per_page' => 1);
$announcements = new WP_Query($args);

if ($announcements->have_posts() ) : while( $announcements->have_posts() ) : $announcements->the_post(); ?>    
    <h1><?php the_title() ?></h1>
    <div class='post-content'><?php the_content() ?></div>
<?php endwhile; endif; ?>

Note, I did two things:

  1. Created an $args array and passed it to the WP_Query constructor.
  2. Check whether or not it returned any posts by doing if ($announcements->have_posts()) before the while loop.

Take a look at this for lots of information on the WP_Query class http://wp.smashingmagazine.com/2013/01/14/using-wp_query-wordpress/

share|improve this answer
add comment

Your Answer

 
discard

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

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