• Resolved flypadre

    (@flypadre)


    On my index page I have a section that displays “the latest news” which is simply the content taken from a specific post. I don’t need a loop because I only want to display information from 1 particular post whose contents gets edited when needed. This is my code to get what I want:

    <?php if (have_posts()) {
       $mypost = get_post(1, ARRAY_A); ?> /*Here I choose the post with ID 1*/
       <h2><?php echo $mypost['post_title']; ?></h2>
       <p><em><?php echo $mypost['post_date']; ?></em></p>
       <p><?php echo $mypost['post_content']; ?></p>
     <?php } else { ?>
       <h2><?php echo "There are no posts.";} ?>

    I am just wondering if there is a better way to do this?
    Also, I would like to format the time stamp neatly, like what is done in the loop, but I am thinking that I would have to write my own function for that. Is there a function that does that already that works outside of the loop?

Viewing 2 replies - 1 through 2 (of 2 total)
  • The only thing that I’d change is to get the post and tehn check to see if it’s there. Like:

    <?php $my_post = get_post(1, ARRAY_A); ?>
    <?php if (!is_null ($my_post)): ?>
        <h2><?php echo $mypost['post_title']; ?></h2>
        <p><em><?php echo date ("jS F Y", strtotime ($mypost['post_date'])); ?></em></p>
    <?php else: ?>
        <h2>There are no posts</h2>
    <?php endif; ?>

    As for formatting the timestamp, you can look at the PHP man page for date() to find out the various formatting options that are available.

    Moderator bcworkz

    (@bcworkz)

    I agree there is no reason to run a loop for a single post, but for whatever reasons all the default themes run a loop on the single post templates. I’d be curious to know why.

    There is a certain elegance in doing something the same way no matter what, but not enough reason to change what you have.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Best code practice for displaying 1 post’ is closed to new replies.