Site logo

[Resolved] Query loop order by custom field (ASC/DSC)

Home Forums Support [Resolved] Query loop order by custom field (ASC/DSC)

Home Forums Support Query loop order by custom field (ASC/DSC)

Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #2565092
    Alex

    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

    #2565157
    Ying
    Staff
    Customer Support

    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/

    #2567506
    Alex

    Awsome! Thank you!

    #2567606
    Ying
    Staff
    Customer Support

    You are welcome   🙂

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