skip to Main Content

I’m trying to sort posts by title (instead of date) within a custom post type archive in Elementor. I’ve set up a custom query and trying to target the custom post type ‘glossary’ but I’m doing something wrong… can anyone help?

    add_action( 'pre_get_posts', 'glossary_sort_order'); 
        function glossary_sort_order($query){
            if(is_post_type_archive( $post_type, 'glossary', true )):
            $query->set( 'order', 'ASC' );
            $query->set( 'orderby', 'title' );
            endif;    
        };

Thank you

2

Answers


  1. Chosen as BEST ANSWER

    The previous answer still didn't work for me, although I do appreciate the helpful feedback from @amarinediary

    Here is the code that eventually worked for me:

    add_action( 'elementor/query/glossary_archives', function ( $query ) {
    $query->set( 'posts_per_page', 1000 );
    $query->set( 'order', 'ASC' );
    $query->set( 'orderby', 'title' );
    

    });

    Thank you


  2. You were close! pre_get_posts is the right action hook, but you’ve got to check if it’s the main query too.
    We also want to exclude the admin side (really important) with ! is_admin(), finally we check if we are on an archive.php page and we check the post type using get_query_var().

    <?php
    /**
    * do_action_ref_array( 'pre_get_posts', WP_Query $this )
    *
    * @param  $this  WP_Query
    * @link https://developer.wordpress.org/reference/hooks/pre_get_posts/
    */
    add_action( 'pre_get_posts', function ( $query ) {
      if ( ! is_admin() && $query->is_archive() && $query->is_main_query() ) { // ... the exclamation point "!" is a logical php operators, means NOT, @see https://www.php.net/manual/en/language.operators.logical.php
        if ( get_query_var( 'post_type' ) == 'glossary' ) { // ... we could combine both if statements, I prefer it like that
          // ... stuff to modified on the main query
          $query->set( 'post_type', array( 'glossary' ) ); // ... here as a redundancy, can be omitted
          $query->set( 'posts_per_page', -1 ); // ... speak for itself, -1 to display all associated posts
          $query->set( 'order', 'ASC' );
          $query->set( 'orderby', 'title' );
        };
      };
    } ); ?>
    

    Learn more

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search