0

I'm trying to output the last (chronologically) 4 posts having the tag (slug) "pp".

<ul>
<?php
$args = array( 'posts_per_page' => 4, 'taxonomy' => 'tag', 'field' => 'slug', 'terms' => 'pp' );
$tag_posts = get_posts( $args );
foreach ( $tag_posts as $post ) : 
  setup_postdata( $post ); ?>
    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endforeach; 
wp_reset_postdata(); ?>
</ul>

This snippet though output 4 entries of the same post, which is the fourth from last! How come? :)

4
  • Try to add a wp_reset_query() before get_posts. Commented Nov 30, 2013 at 13:36
  • Uhm, doesn't work anymore with that :P Commented Nov 30, 2013 at 13:38
  • Before the foreach loop do var_dump( $tag_posts ); so you can see if they really are the same post.
    – Chris_O
    Commented Nov 30, 2013 at 14:07
  • The result is NULL. The permalink is correct though (it's the one that title says). Commented Nov 30, 2013 at 14:16

1 Answer 1

2

This is because you are not passing the parameters in the correct way, taxonomy param needs to be passed under tax_query. Please replace the $args with the below:--

$args = array(
    'posts_per_page' => 4,
    'tax_query' => array(
        array(
            'taxonomy' => 'tag',
            'field' => 'slug',
            'terms' => 'pp'
        )
    )
);

For more details check the codex

5
  • I tried but with but now output is blank New snippet: pastebin.com/raw.php?i=kQLFeetN Commented Nov 30, 2013 at 14:53
  • oops, posts_per_page has a ' where it shouldn't. Commented Nov 30, 2013 at 14:53
  • Uhm, stil no luck Commented Nov 30, 2013 at 14:55
  • can you tell me what does var_dump($tag_posts) return here. Please try it before the foreach loop and let me know Commented Nov 30, 2013 at 15:10
  • Try the code now, there was an apostrophe after 4, Rarst has edited it. please try the above code now Thanks @Rarst Commented Nov 30, 2013 at 15:26

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.