0

I would like to display a "next link" at the bottom of several page templates, using the actual custom menu in which they sit in. I built a function that mostly works except for an edge case (explained further). I wonder if you might see an obvious mistake of mine that could explain these?

Here is my function (inside functions.php)

/*
    FIND WHAT IS THE NEXT MENU ITEM FROM A GIVEN PAGE TEMPLATE
    used in The School pages to present teaser (bottom of the pages)

    usage: $next_post = get_next_menu_item('menu-id-name');
*/
function get_next_menu_item($menu_name){
    global $post;
    $menu = wp_get_nav_menu_object( $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 );
        if ($id == $post->ID){
            $next_id = $i;
        }
    endforeach;
    $next = $menuitems[$next_id+1];
    $next = get_post_meta( $next->ID, '_menu_item_object_id', true );
    return get_post($next);

}

Case where it returns a wrong menu object

I have a custom post type "staff". To be able to have a link to its content from the custom menus, I've created a page using the archive-staff.php template. On that page, my function retrieves an incorrect post.

The staff template recreates the main loop independently from the query_vars. Here it is, just in case it is important.

global $wpdb;
global $post;

$sql = "SELECT * FROM `bj_posts` p

LEFT JOIN (
    SELECT post_id, meta_value as purpose
    FROM `bj_postmeta` pm 
    WHERE  `meta_key`='_staff_purpose'
    ) pm ON p.ID=pm.post_id
WHERE p.`post_type`='staff' AND p.`post_status`='publish'
ORDER BY purpose ASC, post_title ASC";

$staff_members = $wpdb->get_results($sql, ARRAY_A);

Results through which I loop, and before calling my function, I reset the query.

 wp_reset_query();
wp_reset_postdata();
$next_page = get_next_menu_item('the-school');
0

It turns out i solved the problem by renaming my Staff template from archive-staff.php to page-staff.php (or anything else for that matter), thus specifically telling Wordpress not to trust the template hierarchy logic and to consider that url as a "page" url, not a custom post type archive.

If you happen to have a use for this function, be aware that it will mainly work for page templates. Anything else needs to be tested, and post archives will not work.

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.