0

I have tried a lot but didn't got a proper result. Someone please check my code, where I am doing mistake.

I want to show other posts with same categories but not the post shows on single page also previous and next post of the current post. Is there any other way to show?

$thisid = get_the_ID();
$prevpost = get_previous_post();
$previd = $prevpost->ID;
$nextpost = get_next_post();
$nextid = $nextpost->ID;
$excludearray = array($previd, $thisid, $nextid);

$args = "posts_per_page=4&exclude=$thisid,$previd,$nextid&cat=";
$categories = get_the_category();
$i = 1;
foreach ($categories as $category) {
    if ($i == 1) {
        $args .= $category->term_id;
    } else {
        $args .= "," . $category->term_id;
    }
    $i++;
}
$query = new WP_Query($args);
if ($query->have_posts()):
    while ($query->have_posts()):
        $query->the_post();
    endwhile;
endif;

Thanks.

3

Have a look at https://codex.wordpress.org/Class_Reference/WP_Query, and maybe try passing your args in an array. Above page lists this exact example, which should work:

// This WILL work
$exclude_ids = array( 1, 2, 3 );
$query = new WP_Query( array( 'post__not_in' => $exclude_ids ) );
|improve this answer|||||
  • But how to use this array as a string, though i have later generating and adding a string to the first query inside foreach. – Satrughna Sethy Sep 22 '17 at 4:53
  • That's the thing: you shouldn't use a string. Use one of the category params instead, in your array: codex.wordpress.org/Class_Reference/…. Like category__in, which expects an array of category IDs. – Jan Boddez Sep 22 '17 at 7:56
0

Thanks all for guiding me, I just changed the code. Below I am writing my ans.

$thisid = get_the_ID();
$prevpost = get_previous_post();
$previd = $prevpost->ID;
$nextpost = get_next_post();
$nextid = $nextpost->ID;
$excludearray = array($previd, $thisid, $nextid);

$exclude_ids = array($previd, $thisid, $nextid);
$args = array(
    "posts_per_page" => 4,
    "post__not_in" => $exclude_ids
);
$categories = get_the_category();
$i = 0;
$cat = array();
foreach ($categories as $category) {
    $cat[$i] = $category->term_id;
    $i++;
}
$cats = array(
    "category" => $cat
);
$args = array_merge($args, $cats);
$query = new WP_Query($args);

if ($query->have_posts()):
    while ($query->have_posts()):
        $query->the_post();
            //Some design stuff.
    endwhile;
endif;
wp_reset_query();
|improve this answer|||||
-1

You are get_posts() arguments in WP_Query. Just use get_posts() instead.

|improve this answer|||||

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.