I have a custom post type "Scholars" that has an archive. I want to sort by a custom meta field called "year", I'm doing this with pre_get_posts
:
add_action('pre_get_posts', 'my_queries');
function my_queries($query)
{
if (!$query->is_main_query()) return;
if ($query->query['post_type'] == 'scholars') {
$query->set('posts_per_page', -1);
$query->set('meta_key', 'year');
$query->set('orderby', 'meta_value');
}
}
This works fine in the archive page (the main listing), but the next_post_link
and previous_post_link
are not in sync in the single post. They are still sorted by date and not by custom "year".
I have a custom query on the single page using WP_Query
to show related posts, but I tried removing it and still does not work.
This is the archive page:
<div class="large-12 columns">
<?php
if (have_posts()) {
while (have_posts()) {
the_post();
// this just loads an <article>
get_template_part('content', 'scholars');
}
} else {
echo '<h2>Nothing found.</h2>';
}
?>
</div>
And this is the single page:
<?php the_post() ?>
<div class="large-12 columns">
<nav class="scholars-navigation">
<span class="prev"><?php previous_post_link() ?></span>
<h2><?php the_title() ?></h2>
<span class="next"><?php next_post_link() ?></span>
</nav>
</div>
<div class="large-3 columns scholar-info">
<img src="<?php the_field('photo') ?>" alt="" />
<h3><?php the_field('year') ?> Scholar</h3>
</div>
Any ideas why it won't work?
Edit: After looking at other related answers seems like this is not possible with the built-in function out of the box, found this plugin but I'm open to any solution.
Edit: Pfff, it doesn't even work with that plugin, don't know what the issue is:
next_post_link_plus('meta_key=year&order_by=numeric')