Support » Plugins » Hacks » get_posts() not working as expected for alphabetical previous/next post query

  • I know similar questions have been asked here, but those I found are very old and/or related to specific plugins.

    I have registered a custom post type–“author_artist”–and I wish to sort the posts alphabetically by author/artist last name. I have created a custom field (_acf_alpha-name-title) to store the name in last name, first name format. I have successfully sorted my posts archive using this field. However, I am having trouble getting the single-post previous post links to work correctly.

    I have set up the following query args to use with get_posts() to retrieve the previous/next posts (using the post entitled Bob Smith (Smith, Bob) as an example):

    // Previous Post
    $args = array(
      'post__not_in' => array(get_the_ID()),
      'posts_per_page' => 1,
      'post_type' => 'author_artist',
      'post_status' => 'publish',
      'orderby' => 'meta_value',
      'meta_key' => '_acf_alpha-name-title',
      'order' => 'DESC',
      'meta_query' => array(
        array(
          'key' => '_acf_alpha-name-title',
          'value' => 'Smith, Bob',
          'compare' => '<'
        )
      )
    );

    and

    // Next Post
    $args = array(
      'post__not_in' => array(get_the_ID()),
      'posts_per_page' => 1,
      'post_type' => 'author_artist',
      'post_status' => 'publish',
      'orderby' => 'meta_value',
      'meta_key' => '_acf_alpha-name-title',
      'order' => 'ASC',
      'meta_query' => array(
        array(
          'key' => '_acf_alpha-name-title',
          'value' => 'Smith, Bob',
          'compare' => '>'
        )
      )
    );

    The Next query seems to work fine, but the Previous query ignores my order designation of DESC. If I set posts_per_page to 1, I get the very first author alphabetically (e.g., Mary Ames) rather than the author immediately before Bob Smith. If I set posts_per_page to -1 (all posts), I get an array of all authors before Bob Smith and the array is sorted in ascending order.

    Am I not doing this correctly? What am I missing?

    One solution I found is to set posts_per_page to -1 and then use the array_keys() function to get the array keys from the resulting posts array. Then I use the max() function to get the highest key for Previous and the min() function to get the lowest key for Next. This works, but it’s inefficient to fetch all posts when I just need one, and I still don’t understand why my DESC order setting is being ignored.

  • The topic ‘get_posts() not working as expected for alphabetical previous/next post query’ is closed to new replies.