DidouS

Sort adjacent post to title

May 6th, 2021 (edited)
431
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Customize Adjacent Post Link Order
  3.  *
  4.  * https://wordpress.stackexchange.com/a/95969/89938
  5.  */
  6. function wpse73190_gist_adjacent_post_where($sql) {
  7.    
  8.     if ( !is_main_query() || !is_singular( 'post' ) ) return $sql;
  9.  
  10.     $the_post = get_post( get_the_ID() );
  11.     $patterns = array();
  12.     $patterns[] = '/post_date/';
  13.     $patterns[] = '/\'[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}\'/';
  14.     $replacements = array();
  15.     $replacements[] = 'post_title';
  16.     $replacements[] = "\"" . $the_post->post_title . "\"";      // add " " when using post_title
  17.     return preg_replace( $patterns, $replacements, $sql );
  18.   }
  19.   add_filter( 'get_next_post_where', 'wpse73190_gist_adjacent_post_where', 10, 2 );
  20.   add_filter( 'get_previous_post_where', 'wpse73190_gist_adjacent_post_where', 10, 2 );
  21.  
  22.   function wpse73190_gist_adjacent_post_sort($sql , $post) {
  23.    
  24.     if ( !is_main_query() || !is_singular( 'post' ) ) return $sql;
  25.  
  26.     $pattern = '/post_date/';
  27.     $replacement = 'post_title';
  28.     return preg_replace( $pattern, $replacement, $sql );
  29.   }
  30.   add_filter( 'get_next_post_sort', 'wpse73190_gist_adjacent_post_sort', 10, 2 );
  31.   add_filter( 'get_previous_post_sort', 'wpse73190_gist_adjacent_post_sort', 10, 2 );
RAW Paste Data