I have function which gets menu next and previous item url. I want to get also title for them. How can I do this? This is what i have :
<?php
$menu_name = 'main-menu';
$locations = get_nav_menu_locations();
$menu = wp_get_nav_menu_object( $locations[ $menu_name ] );
$menuitems = wp_get_nav_menu_items( $menu->term_id, array( 'order' => 'DESC' ) );
$i=-1;
foreach ( $menuitems as $item ):
$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];
}
?>
<a href="<?php echo $nextid; ?>">Next Item</a>
<a href="<?php echo $previd; ?>">Previous Item</a>
Destination point is to replace ‘next item’ and ‘previous item’ with wp_nav_menu’s next and prev item titles. Is that possible with this function? Any answer will be helpful!
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
To get a post title by ID you need: get_the_title( $id );.
You can integrate this into your code using a similar method for how this has been done for the URL’s with $link, but that’s basically a PHP coding question, so it’s best to get as far as you can with the code and then post again if you get stuck.
Method 2
<?php
$menu_name = 'primary';
$locations = get_nav_menu_locations();
$menu = wp_get_nav_menu_object( $locations[ $menu_name ] );
$menuitems = wp_get_nav_menu_items( $menu->term_id, array( 'order' => 'DESC' )
);
$i=-1;
foreach ( $menuitems as $item ):
$i++;
$id = get_post_meta( $item->ID, '_menu_item_object_id', true );
$page = get_page( $id );
$link = get_page_link( $id );
$title = get_the_title( $id );
$linkarray.=$id.",";
$urlarray.=$link.",";
$titlearray.=$title.",";
if ($id==$post->ID){
$previd=$i-1;
$nextid=$i+1;
$titleid=$i+1;
}
endforeach;
$linkarray=explode(',',$linkarray);
$urlarray=explode(',',$urlarray);
$titlearray=explode(',',$titlearray);
$titleid=$titlearray[$titleid];
$nextid=$urlarray[$nextid];
if (empty($nextid)){
$nextid=$urlarray[0];
}
$previd=$urlarray[$previd];
if (empty($previd)){
$previd=$urlarray[$i];
}
?>
<?php echo $titleid; ?>
This is the edited working version, in case if somebody will need.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0