Support

Account

Home Forums General Issues Next post in relationship field Reply To: Next post in relationship field

  • Ok, I eventually solved it, but I must admit it isn’t the cleanest way of doing it. I followed the idea to put all items in an array, and select the one before (and after) the current position.

    First I retrieved the list of projects to show.

    
    $posts = get_field('projectSelector', 42); // include id of page to get it to work propperly
    

    Then create two functions:

    
    function prev_link($posts, $current) {
        for ($i = 0; $i < count($posts); $i++) {
            if ($current->ID == $posts[$i]->ID) {
                if (isset($posts[$i-1])) {
                    return $posts[$i-1];
                }
            }
        }
        return $posts[count($posts)-1];
    }
     
    function next_link($posts, $current) {
        for ($i = 0; $i < count($posts); $i++) {
            if ($current->ID == $posts[$i]->ID) {
                if (isset($posts[$i+1])) {
                    return $posts[$i+1];
                }
            }
        }
        return reset($posts);
    }
    

    Next step is to create the links:

    
    if ($posts) {
        $post = prev_link($posts, $post);
        setup_postdata($post);
    ?>
        <a href="<?php echo get_permalink($post->ID); ?>" class="prev-post-button"><?php e_i18n("Vorig project", "Previous project"); ?></a>
    <?php
        wp_reset_postdata();
    }
     
        $post = next_link($posts, $post);
        setup_postdata($post);
    ?>
         
        <a href="<?php echo get_permalink($post->ID); ?>" class="next-post-button"><?php e_i18n("Volgend project", "Next project"); ?></a>
     
    <?php
     
        wp_reset_postdata();
     

    Setting up the post data is necessary to obtain the right post ID’s.

    Notice that the prev link picks the previous from the current, and the next the next from the current. I’m also checking where in the array I am, so that when I am at the start or the end, it returns the last or the first from the array.

    Hope this will help you guys with this issue. I got some help from @thijsw