If you want to use the the_
functions (e.g. the_permalink()
and the_title()
) and including in_category()
(without specifying the second parameter) outside of The Loop (the standard one which calls the_post()
), you should access the global $post
variable and call setup_postdata()
to set up global post data and after your foreach
ends, call wp_reset_postdata()
to restore the $post
back to the current post in the main query.
You also must rename the $post_item
variable to $post
and I’d also use OBJECT
as the second parameter value for wp_get_recent_posts()
, although you could actually do setup_postdata( (object) $post )
.
Working Example
$recent_posts = wp_get_recent_posts( array(
'numberposts' => 6, // Number of recent posts to display
'post_status' => 'publish' // Show only the published posts
), OBJECT ); // 1. Set the second parameter to OBJECT.
global $post; // 2. Access the global $post variable.
foreach ( $recent_posts as $post ) : // 3. Rename $post_item to $post
setup_postdata( $post ); // 4. Set up global post data.
// ... your code here ..
echo ( in_category( 'members' ) ? 'In' : '<b>Not</b> in' ) . ' Members category';
the_title( '<h3>', '</h3>' );
endforeach;
wp_reset_postdata(); // 5. Restore the $post variable.
Remember, you need to change the $post_item
in your code to $post
and use the “arrow” to access the post data, e.g. $post->ID
and not $post['ID']
! 🙂