0

I want to show Previous category and Next category links in a category archive page in woocommerce template. I got this code from another post but for me errors are coming. These are the errors,

Catchable fatal error: Object of class WP_Error could not be converted to string in [FILE] and undefined variable for $next_cat and $prev_cat

$this_category = get_queried_object();
$categories = get_categories();

foreach( $categories as $position => $cat ) :
if( $this_category->term_id == $cat->term_id ) :
    $next_cat = $position + 1;
    $prev_cat = $position - 1;
    break;
endif;
endforeach;

$next_cat = $next_cat == count($categories) ? 0 : $next_cat;
$prev_cat = $prev_cat < 0 ? count($categories) - 1 : $prev_cat;

echo 'previous: ' . get_term_link( $categories[$prev_cat] );
echo 'next: ' . get_term_link( $categories[$next_cat] );

Any help is appreciated.

closed as off-topic by Mark Kaplun, Dave Romsey, Howdy_McGee Oct 10 '16 at 22:19

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions that are too localized (such as syntax errors, code with restricted access, hacked sites, hosting or support issues) are not in scope. See how do I ask a good question?" – Mark Kaplun, Dave Romsey, Howdy_McGee
If this question can be reworded to fit the rules in the help center, please edit the question.

  • it is impossibke to remoteky debug things you should investigate and fix the errors you get – Mark Kaplun Oct 5 '16 at 8:01
0

This is about PHP, not about WordPress, but here you go: get_categories returns a simple array of categories, not an indexed array. Your foreach loop tries to adress it as an indexed array. Hence the error. Also, $position becomes an undefined variable, and the loop is unnecessary anyway.

$position = array_search ($this_category->term_id, $categories);
$next_cat = $position + 1;
$prev_cat = $position - 1;

Please make sure get_categories is returning an array of ID's and not something else.

  • Yes, This suggestion deleted errors and i am getting links also, but I am getting same category link for both Next and previous links (i.e present category link) – Dreamerz Oct 5 '16 at 8:57
  • you could debug this by echoing intermediate results: $position, $next_cat, $categories[$next_cat]. This will tell you where things go wrong. – cjbj Oct 5 '16 at 9:02
  • That helped, Many Thanx – Dreamerz Oct 5 '16 at 9:43

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