WordPress.org

Forums

get_posts() pulling incorrect data (5 posts)

  1. cpettican
    Member
    Posted 2 years ago #

    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

  2. cpettican
    Member
    Posted 2 years ago #

    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.

  3. claybaby
    Member
    Posted 1 year ago #

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

  4. AndreyPutilov
    Member
    Posted 1 year ago #

    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.

  5. stbedesantafe
    Member
    Posted 1 year ago #

    **! 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?

Topic Closed

This topic has been closed to new replies.

About this Topic