0

My first real day with Wordpress, it's not going well... I just have a simple loop where I wish to display some posts from a specific category. This is my code:

<?php 
    $args = array(
        'numberposts' => 5,
        'category' => 2,
        'offset' => 0,
        'order' => 'date',
        'post_type' => 'post',
        'post_status' => 'publish'
    );
    $foodPosts = get_posts($args);
    foreach ($foodPosts as $foodPost) : setup_postdata($foodPost); 
?>
    <div><?php the_permalink(); ?></div>
    <div><?php the_title(); ?></div>
    <div><?php the_content(); ?></div>
<?php endforeach; wp_reset_postdata(); ?>

and this is the output:

http://10.0.1.174/mysite/?p=7
Cool post title
this is yet another food post

http://10.0.1.174/mysite/?p=7
Cool post title
this post is in the food category

http://10.0.1.174/mysite/?p=7
Cool post title
this is a post about food

So the content for each is correct, but some reason all the permalinks and titles are the same as the very first post. What's up?

  • The codex page for setup_postdata explains why this is happening, see the examples on that page. – Milo Apr 12 '17 at 12:18
3

Try using WP_Query instead. So the code would be like:

<?php 
    $args = array(
        'posts_per_page' => 5,
        'cat' => 2,
        'offset' => 0,
        'order' => 'date',
        'post_type' => 'post',
        'post_status' => 'publish'
    );
    $post_query = new WP_Query($args);

    if($post_query->have_posts()) : while($post_query->have_posts()) : $post_query->the_post();   
?>
    <div><?php the_permalink(); ?></div>
    <div><?php the_title(); ?></div>
    <div><?php the_content(); ?></div>
<?php
endwhile;
endif;
wp_reset_postdata();
?>
  • Worked great, cheers. Wonder what the problem was with the standard methods – Jazcash Apr 12 '17 at 12:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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