WordPress.org

Support

Support » Themes and Templates » last three posts in a category

last three posts in a category

  • I would like to display just the titles of the last three posts in a category. Here is the code I wrote that works, but it messes up my entire page. I am pasting the code on my homepage (I don’t know if that makes a difference). Is there a better way to do this?

    <?php $temp_query = $wp_query; ?>
    <?php query_posts('cat=4&showposts=3'); ?>
    <?php while (have_posts()) : the_post(); ?>
    <h5 id="post-<?php the_ID(); ?>"><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></h5>
    <?php endwhile; ?>
    <?php $wp_query = $temp_query; ?>
Viewing 7 replies - 1 through 7 (of 7 total)
  • esmi

    @esmi

    Forum Moderator

    So using get posts is a better option. If I am understanding what the Codex says this is more all the lines of what I should be using:

    global $post;
    $args = array( 'posts_per_page' => 3, 'category' => 4 );
    $myposts = get_posts( $args );
    foreach( $myposts as $post ) :	setup_postdata($post); ?>
    	<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>

    esmi

    @esmi

    Forum Moderator

    Yes. get_posts and WP_Query are far better for creating secondary Loops.

    What am I missing to make this work:

    global $post;
    $args = array( 'posts_per_page' => 3, 'category' => 4 );
    $myposts = get_posts( $args );
    foreach( $myposts as $post ) :	setup_postdata($post); ?>
    	<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>

    Michael

    @alchymyth

    Forum Moderator

    you’re missing the <?php endforeach; ?>

    also, you might need to explain in more detail, what ‘but it messes up my entire page’ means, or even better, post a link to your site to illustrate the problem.

    I have been working on this site for nearly 2 months now and there are only a few issues left to straight out.

    On my homepage under What’s New and Coming Soon I would like to include the titles of the last three posts in those categories.
    At my index page I included the code <?php include_once('includes/latest.php'); //include latest articles ?>

    And the code for latest.php it is: http://pastebin.com/f3jjwfVB

    Right now the code that is in latest.php is the code that came with the template. Their code displays the title of the latest post no matter what the category. I don’t want that. I want the last three posts in any specific category. If I insert my code the way it is now the page only loads until it reaches the div titled left.

    esmi

    @esmi

    Forum Moderator

    Their code displays the title of the latest post no matter what the category.

    No – that code pulls the 3 latest posts from category 4.

Viewing 7 replies - 1 through 7 (of 7 total)
  • The topic ‘last three posts in a category’ is closed to new replies.
Skip to toolbar