Order Query loop with Post Meta by ASC / DSC

  • Hi, i have a post meta query loop to current post, post meta is actually a bi-relationship field to show related reviews..

    Can i filter those reviews by ASC / DSC? I wanna show latest reviews first. Currently i’m seeing i can drag drop the order…

  • Hi there,

    Can you try this snippet?

    add_filter( 'generateblocks_query_data', function( $query_data, $query_type, $attributes ) {
        if ( 'post_meta' !== $query_type ) {
            return $query_data;
        }
        $classes = preg_split( '/\s+/', $attributes['className'] ?? '' );
        if ( ! in_array( 'relationship_sort', $classes, true ) ) {
            return $query_data;
        }
        if ( empty( $query_data['data'] ) || ! is_array( $query_data['data'] ) ) {
            return $query_data;
        }
        $get_post_id = function( $item ) {
            if ( is_numeric( $item ) ) {
                return absint( $item );
            }
            if ( is_object( $item ) ) {
                return absint( $item->ID ?? $item->id ?? 0 );
            }
            if ( is_array( $item ) ) {
                return absint( $item['ID'] ?? $item['id'] ?? 0 );
            }
            return 0;
        };
        usort( $query_data['data'], function( $a, $b ) use ( $get_post_id ) {
            $a_id = $get_post_id( $a );
            $b_id = $get_post_id( $b );
            $a_time = $a_id ? get_post_time( 'U', true, $a_id ) : 0;
            $b_time = $b_id ? get_post_time( 'U', true, $b_id ) : 0;
            // Latest first. Swap $b_time and $a_time for oldest first.
            return $b_time <=> $a_time;
        } );
        return $query_data;
    }, 11, 3 );

    Then on the Post Meta Query block, add the relationship_sort class under Advanced > Additional CSS Classes.

    Let us know how it goes.

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