How to create Alphabetic pagination with range?

Currently, I am trying to create an alphabetic pagination with ranges for a custom post type on a custom field using this code from kathy is awesome. I have gotten everything working except for the range aspect of it. Such as A-E, F-H and so on. Any help would be great. Thanks.

Related posts

1 comment

  1. If you have used that code, now you have a custom taxonomy called ‘glossary’, what you need to show the range is a custom query like

    new WP_Query( array(
      'tax_query' => array(
         array(
           'taxonomy' => 'glossary',
           'field' => 'slug',
           'terms' => range('a', 'e')
         )
       )
    ) );
    

    The problem is how to perform this query with a url?

    You can make use of an endpoint, something like

    add_action('init', 'add_glossary_range_endpoint');
    
    function add_glossary_range_endpoint() {
        add_rewrite_endpoint( 'letters', EP_ROOT );
    }
    

    Doing so, when you visit the link http://example.com/letters/a-e/ a variable ‘letters’ is added to the query and you can intercept it and use for your scope using pre_get_posts hook

    add_action('pre_get_posts', 'glossary_range_query');
    
    function glossary_range_query( $query ) {
      if ( ! is_admin() && $query->is_main_query() && $query->get('letters') ) {
         $letters = explode('-', $query->get('letters') );
         if ( count($letters) == 2 ) {
            $tax_query = array(
              'taxonomy' => 'glossary',
              'field' => 'slug',
              'terms' => range($letters[0], $letters[1])
            );
            $query->set('tax_query', array($tax_query) );    
            $query->set('letters', NULL );     
         }
      }
    }
    

    Now you have to visit the Settings->Permalinks page on your backend and save changes to flush rewrite rules and then you are done.

    Now probably you have to create a fucntion to show the link to range pages, something like:

    function get_glossary_range_url( $from = 'a', $to = 'z' ) {
      return home_url( '/letters/' . $from . '-' . $to . '/' );
    }
    

Comments are closed.