Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Single page 'recent items' code for/excluding current category WordPress

  • SOLVED

Here's the code I use to show recent items in my site's sidebar.

<ul>
<?php
global $post;
$myposts = get_posts('numberposts=5&offset=0&category=82');
foreach($myposts as $post) :
setup_postdata($post);
?>
<li>
<a href="<?php the_permalink(); ?>">
<img class="sidebarthumbimage"
src="<?php echo catch_that_image() ?>">
<?php the_title(); ?></a><BR>
<span class="sidebartags"><span class="tags">Filed under <?php the_tags(); ?></span></span></li>
<?php endforeach; ?>
</ul>


For use on single pages, I'd like the code to be adapted in two different ways.

1. To show recent items only in the current post's category. ('Recently in this section'.)

2. To show recent items in every section <em>other</em> than the current post's category. ('Recently in other sections'.)

I would like both instances to also exclude the current post.

Answers (1)

2011-03-01

Utkarsh Kukreti answers:

Recently in this section
<ul>
<?php
global $post;
$category = get_the_category($post->ID);
$category = $category[0]->cat_ID;

$myposts = get_posts(array('numberposts' => 5, 'offset' => 0, 'category__in' => array($category), 'post__not_in' => array($post->ID)));
foreach($myposts as $post) :
setup_postdata($post);
?>
<li>
<a href="<?php the_permalink(); ?>">
<img class="sidebarthumbimage"
src="<?php echo catch_that_image() ?>">
<?php the_title(); ?></a><BR>
<span class="sidebartags"><span class="tags">Filed under <?php the_tags(); ?></span></span></li>
<?php endforeach; ?>
<?php wp_reset_query(); ?>
</ul>

Recently in other sections
<ul>
<?php
global $post;
$category = get_the_category($post->ID);
$category = $category[0]->cat_ID;

$myposts = get_posts(array('numberposts' => 5, 'offset' => 0, 'category__not_in' => array($category), 'post__not_in' => array($post->ID)));
foreach($myposts as $post) :
setup_postdata($post);
?>
<li>
<a href="<?php the_permalink(); ?>">
<img class="sidebarthumbimage"
src="<?php echo catch_that_image() ?>">
<?php the_title(); ?></a><BR>
<span class="sidebartags"><span class="tags">Filed under <?php the_tags(); ?></span></span></li>
<?php endforeach; ?>
<?php wp_reset_query(); ?>
</ul>