get_previous/next_post links based on custom query order?

WordPress 4 posts 2 voices

  1. Is it possible to use the previous_post_link and next_post_link based off a custom meta key orderby?

    So i have the following pre_get_posts for my custom post type archive page, its based off a custom orderby number, i/e 1,2,3,4 orders the posts in that order.

    function projects_query_order($query){
            if( ! is_admin() && is_post_type_archive( 'project-work') && $query->is_main_query()  ):
            		$query->set( 'posts_per_page', -1 );
    	        	$query->set( 'meta_key', 'home_page_order' );
                       	$query->set( 'orderby', 'meta_value' );
                       	$query->set( 'order', 'ASC' );
    add_action( 'pre_get_posts', 'projects_query_order', 5 );

    However, once on the single page for that custom post type it obviously is showing the default links, which i think is by date published; rather than the custom order?

    <?php  if( get_previous_post()): ?>
    		<div class="journal-nav_area">
    			Previous Post
    			<?php previous_post_link( '<span class="journal-nav__prev">' . esc_html__( '%link', ’site-design' ) . '</span>', '%title' ); ?>
    		</div> <!--journal-nav_area-->
    		<? endif; ?>
    		<?php  if( get_next_post()): ?>
    		<div class="journal-nav_area">
    			Next Post
    			<?php next_post_link(     '<span class="journal-nav__next ">' . esc_html__( '%link',     ’site-design' ) . '</span>', '%title' ); ?>
    		</div> <!--journal-nav_area-->
    		<? endif; ?>

    Is there anyway to change the previous/next links to that of the custom order?

  2. I’m going to dig into this. The site went down for most of yesterday. And, today, I’ve been celebrating the holiday.

    I’m honestly not sure how to do it, but I’ll see if I can come up with something.

  3. Thank you Justin, appreciate that.

  4. Here’s what I know. There’s a few filter hooks available (see get_adjacent_post() in link-template.php):

    $join = apply_filters( "get_{$adjacent}_post_join", $join, $in_same_term, $excluded_terms, $taxonomy, $post );
    $where = apply_filters( "get_{$adjacent}_post_where", $wpdb->prepare( "WHERE p.post_date $op %s AND p.post_type = %s $where", $current_post_date, $post->post_type ), $in_same_term, $excluded_terms, $taxonomy, $post );
    $sort  = apply_filters( "get_{$adjacent}_post_sort", "ORDER BY p.post_date $order LIMIT 1", $post );

    $adjacent is either previous or next, depending on the context.

    If it were just a basic filter on the “where” or the “sort”, I think I could figure it out. However, throwing post meta in the mix is where I’m unsure. I think you’d need the “join” hook for that.

    SQL queries are not really my thing. I’m even less knowledgeable about handling joins.