WordPress get_next_post based on custom date field

I have a WordPress news site.

The news stories are added as posts.

Read More

To have more control I have a custom date field on the posts.

The posts are displayed in date order using the date in the custom field.

So the order the posts are displayed on the site can sometimes be different from the order of
the posts in the WP backend which are in the date they were added order.

On the single.php page I have a next and prev post links.

The next and prev post links use the order of the posts in WP which can be different from that on the front end.

Can I use the WP next,prev function with a custom date field instead of the actual WP order of posts. So the next and prev links will link to the next and prev links shown in the front end of the site.

Related posts

1 comment

  1. I am not sure there is a solution using get_next_post(), but I guess you could query a single post with a higher/lower date using your custom meta.

    Something like this should work, but I did not test it.

    $args = array(
     'meta_query'=> array(
        array(
          'key' => 'date',
          'compare' => '>=',
          'value' => $currentPostDate,
          'type' => 'DATE',
        )
      ),
     'posts_per_page' => 1
    );
    
    query_posts( $args );
    

    Keep in mind this note from the documentation:

    type (string) – Custom field type. Possible values are ‘NUMERIC’,
    ‘BINARY’, ‘CHAR’, ‘DATE’, ‘DATETIME’, ‘DECIMAL’, ‘SIGNED’, ‘TIME’,
    ‘UNSIGNED’.

    Default value is ‘CHAR’. The ‘type’ DATE works with the
    ‘compare’ value BETWEEN only if the date is stored at the format
    YYYY-MM-DD and tested with this format.

Comments are closed.