Site logo

Archived topic

Query loop order by custom field (ASC/DSC)

3 replies · Started by Alex on March 12, 2023

Viewing posts 1–4 of 4

Hi guys,

Is it possible to order a query loop by a custom field? This is to be used on a separate page not an existing taxonomy archive.

For example:

object_name and then sort all posts alphabetically

Thanks in advance

Hi Alex,

Try following steps:

1. Add a CSS class to the Grid block of the query loop block, eg. order_by_object_name.
Adding CSS class to blocks: https://wordpress.com/support/wordpress-editor/adding-additional-css-classes-to-blocks/

2. Add this PHP code:

add_filter( 'generateblocks_query_loop_args', function( $query_args, $attributes ) {

    // apply filter if loop has class: order_by_object_name
    if (! empty( $attributes['className'] ) && strpos( $attributes['className'], 'order_by_object_name' ) !== false) {
       
        return array_merge( $query_args, array(
            'meta_key' => 'object_name',
            'orderby' => 'meta_value',
            'order' => 'ASC',
        ));
    }
    return $query_args;
}, 10, 2 );

Adding PHP: https://docs.generatepress.com/article/adding-php/

For more info: https://docs.generateblocks.com/article/order-query-loop-by-custom-field/

Awsome! Thank you!

You are welcome   :)

This archived topic is closed to new replies.