1

I'm trying to add a custom loop to display post titles from the category homepage. Here's the code I have so far so, but it's not displaying any posts. BTW, I'm using this code in single.php.

<?php $recentPosts = new WP_Query(); ?>
<?php if ( $recentPosts->have_posts() ) : ?>
    <?php $recentPosts->query_posts( array ( 'category_name' => 'homepage', 'posts_per_page' => 10 ) ); ?>
           <?php while ($recentPosts->have_posts()) : $recentPosts->the_post(); ?>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
    <?php endwhile; ?>
<?php endif; ?>
<?php wp_reset_postdata(); ?>

I'm not too sure what's going on, but would appreciate any help I can get.

1 Answer 1

2

You're doing a lot of unnecessary messing around with your query object. Since you're dealing with an archive page, you should be able to create a new template file called category-homepage.php (assuming the slug of the category is homepage). In it, you could place something like the following:

$args = array(
    'category_name' => 'homepage', 
    'posts_per_page' => 10
);
$recentPosts = new WP_Query( $args );
if ( $recentPosts->have_posts() ) : 
    while ( $recentPosts->have_posts() ) : $recentPosts->the_post(); ?>

    <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>

<?php endwhile; endif; ?>

Again, since it's a category archive page, you shouldn't be doing anything to single.php. You can read more about template hierarchy in the Codex.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.