How to order posts by custom field when using Post Navigation?

Hi!

As default, the Post Navigation element uses post ID for ordering.

Is it possible to use a custom field (number or text) to set a custom order and use that one for Post Navigation?

For example:
I have 3 posts with post id 1, 2, 3 and they have custom field values of 18, 19, 17 respectively.
By default, Post Navigation will lead me through 1 → 2 → 3.
But I want to order them by the custom field, so I would have 3 → 1 → 2

Thank you in advance.

I found this and it works for me: WordPress: sort Previous and Next post by menu_order · GitHub

In case someone comes across this post and, like me, don’t get to solve the issue with the previous answer: I could fix the posts nav order by adding the following PHP code to functions.php file.
Change “event_date” for your meta key. Then instead of the posts navigation element add a shortcode in your page. In this case it’s [event_date_navigation], but you can change it on the last line of the code.


function custom_post_navigation_by_event_date() {
    global $post;

    if (!$post) return '';

    $meta_key = 'event_date';
    $current_event_date = get_post_meta($post->ID, $meta_key, true);

    $next = new WP_Query([
        'post_type' => get_post_type($post),
        'posts_per_page' => 1,
        'meta_key' => $meta_key,
        'orderby' => 'meta_value',
        'order' => 'ASC',
        'meta_query' => [
            [
                'key' => $meta_key,
                'value' => $current_event_date,
                'compare' => '>',
            ]
        ]
    ]);

    $prev = new WP_Query([
        'post_type' => get_post_type($post),
        'posts_per_page' => 1,
        'meta_key' => $meta_key,
        'orderby' => 'meta_value',
        'order' => 'DESC',
        'meta_query' => [
            [
                'key' => $meta_key,
                'value' => $current_event_date,
                'compare' => '<',
            ]
        ]
    ]);

    ob_start();
    echo '<nav class="custom-event-post-navigation">';

    if ($prev->have_posts()) {
        $prev->the_post();
        echo '<div class="nav-previous"><span class="label">← Vorherige Veranstaltung</span><a href="' . get_permalink() . '">' . get_the_title() . '</a></div>';
    }

    wp_reset_postdata();

    if ($next->have_posts()) {
        $next->the_post();
        echo '<div class="nav-next"><span class="label">Nächste Veranstaltung →</span><a href="' . get_permalink() . '">' . get_the_title() . '</a></div>';
    }

    wp_reset_postdata();

    echo '</nav>';

    return ob_get_clean();
}
add_shortcode('event_date_navigation', 'custom_post_navigation_by_event_date');