listing only posts that share two categories in WordPress
by Evil Overlord in
Web Design/WP
during lunch time on
January 14th, 2006:
4 years, 1 month ago
The following code is the result of me asking what I thought would be a simple question in the WordPress forums. I wanted to make a simple list of posts that shared two categories, but only those posts that were in both categories.
I take no credit for the code, I am simply replicating it here for storage/publicity purposes. The real gurus are alphaoide and amory.
I’m not using this anymore, but this is the exact code that I yoinked from my template:
<h2>Video Game Writing</h2>
<?php $my_posts = $wpdb->get_results( "
SELECT * FROM
$wpdb->posts p1,
$wpdb->posts p2,
$wpdb->post2cat c1,
$wpdb->post2cat c2
WHERE
p1.ID = p2.ID AND
p1.ID = c1.post_ID AND
p2.ID = c2.post_ID AND
c1.category_id = 2 AND
c2.category_id = 3
" );
?>
<?php if( $my_posts ) : foreach( $my_posts as $post ) : setup_postdata( $post ); ?>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<?echo " - "; ?>
<?php the_date(); ?>
<?echo "<br />"; ?>
<?php endforeach; endif; ?>
This would produce a simple list of posts that were in both categories 2 and 3 (for me, video games and writing). You can modify the category_id number to suit your needs, and the results can be customized to fit.
This was only tested in WP 1.5.x - I removed it before upgrading to 2.0. If anyone uses it in 2.0 and would like to leave a comment with its working status, that would be great and I’ll update the post, crediting you with the info.
Hope this helps someone else.
WordPress stuff- Project Dolphin Wordpress Plugin released
- listing only posts that share two categories in WordPress
- CSS styling for alternating comment colors with author differentiation in WordPress
