wp_nav_menu查找下一个,以前的链接(wp_nav_menu find next, prev

2019-08-07 06:19发布

我需要设置使用wp_nav_menu一些分页,所以我需要访问一个菜单以前,当前和未来的项目。 有任何想法吗?

Answer 1:

好吧,这里是我想出了 - 和它的作品。

<?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>


Answer 2:

我适应了以前的答案,包括在菜单(不只是网页)的所有项目员额。 此代码返回上一页和下一页的帖子的ID。

<?php
$current_post_id = $post->ID;
$menu_name = 'guide-menu-frontpage';
$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 = 0;

foreach ( $menuitems as $item ){
    $menuitems_id_array[] = $item->object_id;
    if ($item->object_id == $current_post_id){
        $prevMenuPosition = $i - 1;
        $nextMenuPosition = $i + 1;
    }
    $i++;
}

if($prevMenuPosition < 0){
    $prev_id = false;
} else {
    $prev_id = $menuitems_id_array[$prevMenuPosition];
}

if($nextMenuPosition > sizeof($menuitems_id_array) - 1){
    $next_id = false;
} else {
    $next_id = $menuitems_id_array[$nextMenuPosition];
}
?>


文章来源: wp_nav_menu find next, previous links