• Hello,

    I am trying to put my latest post on my static front page using the following php code:

    <?php
     global $post;
     $myposts = get_posts('numberposts=1');
     foreach($myposts as $post) :
     ?>
     <?php the_title(); ?>
     <?php the_content(); ?>
     <?php endforeach; ?>

    For some reason the data that is displayed comes from two different posts. the_title() is returning the correct post title (the most recent), however the_content() is returning the text from my first post, not the most recent. As they both reside in the same loop I don’t really understand what’s going wrong to pull two seperate posts at the same time.

    Has anyone experienced this themselves? Would anyone know what I can do to fix this?

    So far I have tried different php codes, deleting most of the plugins, emptying both the wp_postmeta and wp_posts database tables and re-entering the posts from scratch. I have also reuploaded the wp-includes folder to my server. Nothing so far seems to work..

    Thank you

Viewing 4 replies - 1 through 4 (of 4 total)
  • Thread Starter cpettican

    (@cpettican)

    I modified the code to:

    <?php
    global $post;
    $args = array( 'numberposts' => 1);
    $myposts = get_posts( $args );
    foreach( $myposts as $post ) :	setup_postdata($post); ?>
    <?php the_category(' > ','multiple'); ?>
    <h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
    Posted by <?php the_author_posts_link(); ?> on <?php the_date(); ?>
    <?php the_content(); ?>
    <?php the_tags(); ?>
    <?php endforeach; ?>

    Now it seems to be working Ok.

    thanks cpettican, that’s what I was looking for!

    Hi. I have had absolutely the same problem. There were three lines outputting the_date, the_title and the_excerpt in the same loop, and they printed data from different posts.
    Also notice that I used WP_USE_THEMES as false, I had my own loop with get_posts command. But I had setup_postdata correctly.

    The solution was simple. I didnt declare $post as global. So. dont forget, this is important.

    **! After I thought about it, I changed your line of code to this:

    ‘$args = array( ‘numberposts’ => 1, ‘category_name’ => Feature);’

    and it works. Is this the correct way to format this? !**

    _____________________

    This is exactly the code I need as well. Thanks, cpettican!

    Can you provide code for limiting the category? I have been using:

    ‘$posts = get_posts(‘numberposts=6&category=2′);’

    But I notice your code is:

    ‘$args = array( ‘numberposts’ => 1);’

    Would specifying the category be the in array statement and how would it be formulated?

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘get_posts() pulling incorrect data’ is closed to new replies.