Support

Account

Home Forums General Issues Custom post type navigation ordered by ACF date field

Helping

Custom post type navigation ordered by ACF date field

  • Hi there,

    I have a custom post type called ‘prime-ministers’

    On it’s archive page, it is ordered by an ACF date picker field called serving_period_1_start

    This works as expected

    However on each individual page, when I add Prev?next post navigation buttons, it always orders them by published date. I have tried many variations, and it’s always the same.

    This is my current code:

    	<div class="prime-ministers-post-nav full-width blue-bg">
    	<?php
    	 
    	 /* Infinite next and previous post looping */
    	 if( get_adjacent_post(false, '', true) ) { 
    		 previous_post_link('%link', '&larr; Previous Post');
    	 } else { 
    		 $arg_prev = array(
    			 
    			'post_type' => 'prime-ministers',
    			'meta_key' => 'serving_period_1_start',
    			'order' => 'DESC',
    			'orderby' => 'meta_value_num'
    	
    		  );
    		 $first = new WP_Query($arg_prev); 
    		 $first->the_post();
    		 echo '<a href="' . get_permalink() . '" class="prev-link"> &larr; Previous Post</a>';
    		 wp_reset_query();
    	 }; 
    	 
    	 if( get_adjacent_post(false, '', false) ) { 
    		 next_post_link('%link', 'Next Post &rarr;');
    	 } else { 
    		 $arg_next = array(
    			'post_type' => 'prime-ministers',
    			'meta_key' => 'serving_period_1_start',
    			'order' => 'ASC',
    			'orderby' => 'meta_value_num'
    		 );
    		 $last = new WP_Query($arg_next); 
    		 $last->the_post();
    		 echo '<a href="' . get_permalink() . '" class="next-link">Next Post &rarr;</a>';
    		 wp_reset_query();
    	 }; 
    	 
    	 ?>
    	</div>

    I am going a bit mad here, so any help would be greatly appreciated

  • The functions you are using do not have filters that are easily usable. You would have to manipulate the actual SQL. They will always return something based on the WP post date.

    If you want this to work then you’d have to update the WP post date based on the ACF field value.

    If you don’t want to do that then you’d have to write your own queries.

    I would make the following suggestions.

    • limit the number of posts found to 1
    • for the meta value use the current posts acf field value
    • for the previous post us < for your compare and order DESC to get the post with the first date before
    • for the next post use > for your compare and order ASC to get the first post with the first date after

    You should also be limiting your queries for the first and last post to 1 as well, there is no need to get multiple posts when you only need 1.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.