WordPress Basics: get recent featured images by category
Accessing the most recent featured images by category in order to create a carousel.
Sometimes you want to have an image slider which not only contains the most recent images on your site but does so by category to ensure that all of the categories on your site are included:
Get the categories: $categories=get_categories();
By default this returns the categories in alphabetical order and ignores any empty ones. That's fine by me so I'm not going to fiddle with it. Now we've got our categories we need to loop over them. Don't forget to close your foreach
!
foreach ($categories as $category) :
# code here
endforeach;
Inside that foreach
loop we're going to run a new WP_Query()
, first though we need to set up our args
:
$args = array(
'cat' => $category->term_id,
'post_type' => 'post',
'posts_per_page' => '5' );
This pulls out the first 5 posts in each category. Once we've done that we can run our WP_Query()
.
$images_query = new WP_Query( $args );
if ( $images_query->have_posts() ): ?>
<?php while ( $images_query->have_posts() ) : $images_query->the_post();
if ( has_post_thumbnail() ) : the_post_thumbnail('post-thumbnail', array("class" => "slider_image")); endif;
endwhile;
endif;?>
Excluding a category
In this example I don't want to pull out featured images associated posts in the category 'Blog'
so I added && $category->cat_name != 'Blog'
to the if
statement inside my query.
Argh! I have posts in more than one category and the images are duplicating
To get rid of duplicate posts add the following on the line above your call to get_categories
: $do_not_duplicate = array()
.
Then, under $images_query->the_post();
add: $do_not_duplicate[] = $post->ID;
.
Now, that we have an array containing the ID's of the posts that have already been pulled we can add a line to our $args
to make the query check it: $post__not_in => $do_not_duplicate
.
Voila, no more duplicate images.
Comments powered by Talkyard.