Are you a GenerateCustomer?

Do you have an active GP Premium or GenerateBlocks Pro license key?

Create a GenerateSupport account for GeneratePress and GenerateBlocks support in one dedicated place.

Create an account
Already have a GenerateSupport account? Login

Just browsing?

Feel free to browse the forums. Support for our free versions is provided on WordPress.org (GeneratePress, GenerateBlocks).

Want to become a premium user? Learn more below.

Query Loop Inherit query from template – Display Order

  • I noticed that one site’s archive is is not displaying based on the latest modified date. It’s running an Element with “Inherit query from template”. Do we need a functions snippet to display archives based on the last modified date (most recently modified displaying first)?

  • Hi there,

    Yes, you’ll need a snippet to modify the default query sorting. Try adding this:

    function sort_by_modified_date($query) {
        // Only modify the main query on the frontend
        if (!is_admin() && $query->is_main_query()) {
            // Set orderby to 'modified' to sort by modification date
            $query->set('orderby', 'modified');
            // Set order to 'DESC' for newest first
            $query->set('order', 'DESC');
        }
        return $query;
    }
    add_action('pre_get_posts', 'sort_by_modified_date');
  • Thanks Alvind,

    Can you tell me which is a better snippet. This one of the one you provided:

    function wpb_sort_archives_by_modified_date( $query ) {
        if ( !is_admin() && $query->is_main_query() && $query->is_archive() ) {
            $query->set( 'orderby', 'modified' );
            $query->set( 'order', 'DESC' );
        }
    }
    
    // Hook into pre_get_posts to modify the archive query
    add_action( 'pre_get_posts', 'wpb_sort_archives_by_modified_date' );
  • The code I provided changes the order of posts on every page of the website, displaying the most recently edited ones first.

    The one you provided only affects list pages like category or tag archives, leaving the homepage unchanged. This is usually better because it scopes the change to where it’s needed while keeping the rest of the site working normally.

  • Perfect, thanks Alvind! Got it.

  • You’re welcome!

Viewing 6 posts - 1 through 6 (of 6 total)
  • You must be logged in to reply to this topic.