0
votes

quick Wordpress question.

I want to display the last 30 posts from my category "photos", but to only display the featured image on the relevant page as a link that will take the user to the actual post.

I have managed to do this, but it displays posts from all categories, not the "photos" category. Code I'm using is below.

I'm sure it's simple, but would love to know how to display just the recent posts from the photo category only (as the featured image).

Thanks

<!-- In functions.php -->
function recentPosts() {
	$rPosts = new WP_Query();
	$rPosts->query('showposts=100');
		while ($rPosts->have_posts()) : $rPosts->the_post(); ?>
		<div class="photos">
			<li class="recent">
				<a href="<?php the_permalink();?>"><?php the_post_thumbnail('recent-thumbnails'); ?></a>
			</li>	
		</div>
		<?php endwhile; 
	wp_reset_query();
}


<!-- this is on the page template -->
<?php echo recentPosts(); ?>
3

3 Answers

1
votes

Just add the category selection to your query.

Replace:

$rPosts = new WP_Query();
$rPosts->query('showposts=100');

With:

$rPosts = new WP_Query('category_name=photos&showposts=100');

Reference: http://codex.wordpress.org/The_Loop#Exclude_Posts_From_Some_Category

0
votes

You need to provide the loop argument that you want post only of certain category by providing category id cat=1. Replace 1 with the id of your photos category

<!-- In functions.php -->
function recentPosts() {
    $rPosts = new WP_Query();
    $rPosts->query('showposts=100&cat=1');
        while ($rPosts->have_posts()) : $rPosts->the_post(); ?>
        <div class="photos">
            <li class="recent">
                <a href="<?php the_permalink();?>"><?php the_post_thumbnail('recent-thumbnails'); ?></a>
            </li>   
        </div>
        <?php endwhile; 
    wp_reset_query();
}


<!-- this is on the page template -->
<?php echo recentPosts(); ?>
0
votes

Add the category ID to your query arguments. echo on the last line is redundant by the way. Your function outputs the HTML directly rather than returning it.

Finally your original markup was invalid. An li can't be the child of a div so I've corrected that in my example.

function recentPosts() {
    $rPosts = new WP_Query( array(
        'posts_per_page' => 30,
        'cat'            => 1
        'no_found_rows'  => true // more efficient way to perform query that doesn't require pagination.
    ) );

    if ( $rPosts->have_posts() ) :
        echo '<ul class="photos">'; 

        while ( $rPosts->have_posts() ) : $rPosts->the_post(); ?>
            <li class="recent">
                <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail( 'recent-thumbnails' ); ?></a>
            </li>   
        <?php endwhile; 

        echo '</ul>';
    endif;

    // Restore global $post.
    wp_reset_postdata();
}


<!-- this is on the page template -->
<?php recentPosts(); ?>