|
/ Documentation /Uncategorized/ How to Display Loop Builder Posts in Random Order

How to Display Loop Builder Posts in Random Order

Overview

By default, the Spectra Loop Builder does not include a built-in option to display posts in a random sort order. However, this can be achieved using a simple custom code snippet via the spectra_loop_builder_main_query_args filter hook.

Solution: Add a Custom Code Snippet

Add the following code to the functions.php file of your child theme:

add_filter( 'spectra_loop_builder_main_query_args', function( $query_args ) {
    $query_args['orderby'] = 'rand';
    unset( $query_args['order'] );
    return $query_args;
} );

What This Code Does

  • It hooks into the Loop Builder’s main query arguments using the spectra_loop_builder_main_query_args filter.
  • It sets the orderby parameter to rand, which tells WordPress to fetch posts in a random order on every page load.
  • It removes the order parameter (ASC/DESC) since it is not needed when using random ordering.

Important Notes

  • Always add this code to a child theme to ensure it is not lost when the parent theme is updated.
  • If you do not have a child theme set up, follow this guide: Install Astra Child Theme.
  • This filter applies to all Loop Builder blocks on your site. If you need it to apply only to a specific block, additional conditional logic would be required

Applies To

  • Plugin: Spectra Pro
  • Block: Loop Builder
  • Feature: Query Sort Order — Random
Was this doc helpful?
What went wrong?

We don't respond to the article feedback, we use it to improve our support content.

Need help? Contact Support