Does anyone know how I can display a list of WordPress posts based on the current post pages current category?
For example if I'm currently on post333.html & the category the page falls under is "Drinks".
How would I get the rest of the posts under that category to display in a list as 'suggested topics' on post333.html.
And if the post & category changes so will the list.
The following code should go directly into your template file.
<?php
// Get Other posts in same category
$suggested_posts = get_posts( array(
'category__in' => wp_get_post_categories( $post->ID ), // Retrieve the list of categories for a post.
'numberposts' => 5, // Number of posts
'post__not_in' => array( $post->ID ) // Exclude current post
) );
// If post found
if( $suggested_posts ) {
foreach( $suggested_posts as $post ) {
setup_postdata($post); ?>
<ul>
<li>
<a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a>
<?php the_content('Read the rest of this entry »'); ?>
</li>
</ul>
<?php }
}
wp_reset_postdata();
?>
If you want to use it anywhere then you may create a shortcode like below.
<?php
function yourprefix_suggested_posts( $atts ){
// Get Other posts in same category
$suggested_posts = get_posts( array(
'category__in' => wp_get_post_categories( $post->ID ), // Retrieve the list of categories for a post.
'numberposts' => 5, // Number of posts
'post__not_in' => array( $post->ID ) // Exclude current post
) );
// If post found
if( $suggested_posts ) {
foreach( $suggested_posts as $post ) {
setup_postdata($post); ?>
<ul>
<li>
<a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a>
<?php the_content('Read the rest of this entry »'); ?>
</li>
</ul>
<?php }
}
wp_reset_postdata();
}
add_shortcode( 'suggested_posts', 'yourprefix_suggested_posts' );
?>
Later you can use [suggested_posts] shortcode anywhere.
(Not tested but it should work.)