Order Query Loop by Custom Field

Query loop block offers some built-in orderby parameters as shown. To order your posts by custom field values, follow the steps below.

1. Add an additional CSS class to the Query loop

For example, we’d like to order the query loop by the value of the custom field priority.

Add a specific class name to the Grid block which is directly nested in the Query loop block, eg. order-by-priority.

2. Add the PHP filter

The filter targets the block with the class name order-by-priority and set the orderby parameter to the custom field values.

We will be using these common WP_Query arguments:

  • meta_key: the custom field name.
  • meta_type: the value type of the custom field.
  • orderby: specify the criteria for sorting the results of a query.
  • order: specify the order in which the results of a query should be sorted, ASC for ascending orders, and DESC for descending orders.

Example A: Numeric Values

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

    // apply filter if loop has class: order-by-priority
    if (! is_admin() && ! empty( $attributes['className'] ) && strpos( $attributes['className'], 'order-by-priority' ) !== false) {
       
        $query_args = array_merge( $query_args, array(
            'meta_key' => 'priority',
            'orderby' => 'meta_value_num',
            'order' => 'ASC',
        ));
    }

    return $query_args;
}, 10, 2 );

Example B: Text Values

CHAR stands for “character”. It is the default meta_type used for custom fields in WordPress, you don’t need to specify it in the code.

//CHAR type custom field value
add_filter( 'generateblocks_query_loop_args', function( $query_args, $attributes ) {

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

Example C: Date Values

//DATE type custom field value
add_filter( 'generateblocks_query_loop_args', function( $query_args, $attributes ) {

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