selectively show wordpress posts based on category
Currently I'm using the following code 开发者_Python百科as part of sidebar code for Wordpress (the code works fine):
<ul class="linklist">
<?php $recentPosts = new WP_Query();
$recentPosts->query('showposts=12');
while ($recentPosts->have_posts()) : $recentPosts->the_post();
?>
<li><a href="<?php the_permalink() ?>" rel="bookmark" title="Link to <?php the_title();
?>">
<?php the_title();
?></a> </li>
<?php endwhile;?> </ul>
It shows the last 12 posts. But what I'm looking for is the following; first check what category the current post (the post that is showing based on the permalink) belongs to, and then only list the latest posts that belong to that same category. What should be edited? Thanks!
Take a look at http://codex.wordpress.org/Function_Reference
It sounds like you are going to want get_the_category(). (Posts can belong to multiple categories). Then you are going to want to call get_posts() passing in the category flag and whatever else you want.
This might not be the shortest and smartest solution but it should work this way if I did not include any typos.
Please be aware that posts can have multiple categories and the script below is only interested in the first of them. But you can modify the script and select recent posts for multiple categories, too.
<?php
if (is_single()) :
$post_id = $wp_query->posts[0]->ID; // get id of post
$cats_of_post = get_the_category($post_id); // get categories by post id
$first_cat_id = $cats_of_post[0]->cat_id; // get first category id
$first_cat_name = $cats_of_post[0]->cat_name; // get category name
?>
<div id="widget-container-recent-in-category">
<div class="widget-title">
<h3>Latest posts in <?php echo $first_cat_name; ?>:</h3>
</div>
<div class="widget-content">
<ul>
<?php
global $post;
$posts_in_cat = get_posts('numberposts=5&category='.$first_cat_id);
// iterate over posts in category and output as listitem
foreach($posts_in_cat as $post) :
?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php
endforeach;
?>
</ul>
</div>
</div>
<?php
endif;
?>
This is a new query that can be used mutliple times in a post or page (with php exec enabled) or sidebar and won't conflict with each other or the main WP loop. Change mycategory to your own category name:
<?php $my_query = new WP_Query('category_name=mycategory&showposts=12'); ?>
<?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
<a href="<?php the_permalink() ?>" title="<?php the_title(); ?>">
<?php the_title(); ?></a>
<?php endwhile; ?>
精彩评论