0

I have this function in my child theme's functions.php, whose simple aim is to list a number of posts, only from the category of the current post, but not the current post itself.

It was working fine until tonight, when it started listing posts from all categories, not just the current post's category.

The only change I had made to my site was to update it to WordPress version 3.8. I'm not sure if that has anything to do with it, but I thought it might, since I have a "cloned" site which is still running WordPress 3.7.1, and the exact same function on that site works, doing exactly what I want it to, i.e., it lists a number of posts, only from the category of the current post, but not the current post itself.

Here's the function:

<?php
function list_posts_from_current_category() {
if(is_single()){
$cat_ID = get_the_category($post->ID);
$cat_ID = $cat_ID[0]->cat_ID;
$this_post = get_the_ID();
$PostsPerPage = 5;
query_posts(array('cat' => $cat_ID, 'post__not_in' => array($this_post), 'posts_per_page' => $PostsPerPage, 'orderby' => 'rand'));
while ( have_posts() ) : the_post();
$ThisPermalink = get_permalink();
$ThisTitle = get_the_title();
echo '<a href="'.$ThisPermalink.'">'.$ThisTitle.'</a><br />';
endwhile;
wp_reset_query();
}
}
add_action('do_my_list', 'list_posts_from_current_category');
?>

It's added to the child theme's content.php in the usual manner:

<?php do_action('do_my_list'); ?>

Like I say, it all works as intended in WP 3.7.1, but has somehow come a cropper in WP version 3.8, listing posts from all categories.

Does anyone know what can be wrong with it?

  • What does $cat_ID variable contain? Have you tried to var_dump it? – Krzysiek Dróżdż Dec 16 '13 at 16:36
0

I never found out what stopped the function from working with WP 3.8, but I found that this variant of it does work - and I have no idea why:

<?php
function list_posts_from_current_category() {
if(is_single()){
$tempArray = get_the_category($post->ID);
$FirstCatName = $tempArray[0]->slug;
$this_post = get_the_ID();
$PostsPerPage = 5;
query_posts(array('category_name' => $FirstCatName, 'post__not_in' => array($this_post), 'posts_per_page' => $PostsPerPage, 'orderby' => 'rand'));
while ( have_posts() ) : the_post();
$ThisPermalink = get_permalink();
$ThisTitle = get_the_title();
echo '<a href="<a href="#">ThisPermalink</a>">'.$ThisTitle.'</a><br />';
endwhile;
wp_reset_query();
}
}
add_action('do_my_list', 'list_posts_from_current_category');
?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.