change:
$args=array(
'showposts' => 4,
'category__in' => array(5),
'caller_get_posts'=>1
);
to
$cat_id = get_query_var('cat');
$args=array(
'showposts' => 4,
'category__in' => array($cat_id),
'caller_get_posts'=>1
);
Thread Starter
lolo23
(@lolo23)
Oh brilliant! Thank you. Is there a way I can get it to work in single.php too? (I apologise, I should have thought of this in the first place.) Each post only has one category.
From my notes this bit showing a foreach of the categories:
<?php
//use in single.php or sidebar, if single post, for each category of that post, display 5 posts in that category, excluding the single post.
if ( is_single() ) {
$categories = get_the_category();
if ($categories) {
foreach ($categories as $category) {
// echo "<pre>"; print_r($category); echo "</pre>";
$cat = $category->cat_ID;
$args=array(
'cat' => $cat,
'post__not_in' => array($post->ID),
'showposts'=>5,
'caller_get_posts'=>1
);
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
echo '<h2>More Posts from '. $category->category_description . '</h2>';
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
<?php
endwhile;
} //if ($my_query)
} //foreach ($categories
} //if ($categories)
wp_reset_query(); // Restore global post data stomped by the_post().
} //if (is_single())
?>
Thread Starter
lolo23
(@lolo23)
Thank you, that worked for me. The code I’m using for single.php is
<?php
if ( is_single() ) {
$categories = get_the_category();
if ($categories) {
foreach ($categories as $category) {
// echo "<pre>"; print_r($category); echo "</pre>";
$cat = $category->cat_ID;
$args=array(
'showposts' => 4,
'category__in' => array($cat),
'caller_get_posts'=>1
);
$posts=get_posts($args);
if ($posts) {
foreach($posts as $post) {
setup_postdata($post);
$link = get_permalink($post->ID);
$text = get_post_meta($post->ID, 'listing', true);
if ($link){
echo '<p><a href="'.$link .'">'.$text.'</a></p>';
}
}
}}}
}
?>