How do i get the direct neighbor in a hierarchy

I’ve build a custom post type for a calendar and created a structure like this:

  • 2012 (general parent)
    • January-2012
      • 1-January-2012
        -2-January-2012
    • Februar-2012
      • 1-February-2012
      • 2-February-2012
    • March-2012
      • 1-March-2012
      • 2-March-2012

If I am now on the side for the whole month, I want to display a link to the pages for the previous and next month.

Read More

example: January <– February –> March

I tried *get_previous_posts_link()* and get NULL,
then I set global $post and get NULL too.

Another question, is this in general the right way?
Maybe then I get the post data / link for 31st January?
I’m not sure if *get_previous_posts_link()* considers the hierarchy.

Related posts

1 comment

  1. Well… I don’t think get_previous_posts_link would help you. It only return link to the previous set of posts within the current query. (see previous_posts_link it prints this link, and get_previous_posts_link returns it).

    And quote from Codex:

    Prints a link to the previous set of posts within the current query.

    If you need the values for use in PHP, use get_previous_posts_link().

    Because post queries are usually sorted in reverse chronological
    order, next_posts_link() usually points to older entries (toward the
    end of the set) and previous_posts_link() usually points to newer
    entries (toward the beginning of the set).

    You could try with these plugins:

    But I’m not sure if they will work correctly.

    I always do it with my custom SQL query – it’s more efficient, because you don’t have to select all pages (and all info about these pages).

    function my_get_next_page_link($post_id =null) {
        global $post, $wpdb;
        if ( $post_id === null )
            $p = $post;
        else
            $p = get_post($post_id);
    
        $res_id = $wpdb->get_var(
            $wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE post_type='page' AND post_status='publish' AND post_parent = %d AND menu_order > %d ORDER BY menu_order ASC, ID ASC LIMIT 1", $p->post_parent, $p->menu_order)
        );
    
        if ( !$res_id )
            return null;
        return get_permalink($res_id);
    }
    

    Of course you should write your own SQL query inside this function (it depends on your query params). You can write same function for previous page link.

    PS. Probably it’s not the easiest way of doing it, but it is efficient and very customizable (if you know SQL).

Comments are closed.