1

Let me explain my situation, I have left menu and menu name is a category slug. Now I want to add next and previous button at the bottom of every post which refer the next and previous menu item. here is my code:

<?php
/**
 * Plugin Name:   Next Previous button bootstrap
 * Description:   Super simple plugin to add next and Previous button
 * Version:       1.0.0
 * Author:        Abdus Sattar Bhuiyan
 * Author URI:   https://www.facebook.com/abdus.s.bhuiyan
 */

$cat = get_the_category($id);
print_r($cat); exit;
$cat = $cat[0];
$menu_slug = strtolower($cat->name);

$menuitems = wp_get_nav_menu_items( $menu_slug, array( 'order' => 'DESC' ) );

 $i=-1;
 foreach ( $menuitems as $item ):
    if($item->url =='#')
      continue;

     $i++;

   $id = get_post_meta( $item->ID, '_menu_item_object_id', true );
   $page = get_page( $id );
   $link = get_page_link( $id );

     $linkarray.=$id.",";
     $urlarray.=$link.",";

   if ($id==$post->ID){
     $previd=$i-1;
     $nextid=$i+1;
   }
 endforeach;

 $linkarray=explode(',',$linkarray);
 $urlarray=explode(',',$urlarray);

 $nextid=$urlarray[$nextid];
 if (empty($nextid)){
     $nextid=$urlarray[0];
 }
 $previd=$urlarray[$previd];
 if (empty($previd)){
     $previd=$urlarray[$i];
 }

 $next_prev_btn = '<a href="<?php echo $nextid; ?>">Next Item</a>';
 $next_prev_btn .= '<a href="<?php echo $previd; ?>">Previous Item</a>';


 add_filter( 'the_content', 'add_next_prev_btn' );

 function add_next_prev_btn( $content ) {
         return $content . $next_prev_btn;
 }

This code is working while I keep it inside any template file like 'index.php' but when I create a simple plugin with same code it is not working. To explore the bug I try to print category object. It prints empty array. Whats wrong is going on my code? Or Is it not possible to use this code inside a plugin instead of template file? thanks for your time.

  • Why is most of your code outside of your add_next_prev_btn function? – Milo Jul 22 '18 at 15:34
1

Your code will run when the plugin is first initiated, which will be before the post data has been set up. Move all of your code from $cat = get_the_category($id); up to (but not including) add_filter... inside the function.

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.