Filter the orderby of entries retrieved from database

Support MB Relationships Filter the orderby of entries retrieved from databaseResolved

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #11199
    Content PilotContent Pilot
    Participant

    Is there a way to filter the orderby parameter once I have retrieved a set of entries?

    In the class MB_Relationships_Query, on line 60 sets the orderby parameter, but I need to change it for my use case, sorting all posts by date descending, not by how they were added in the backend. I could change them by hand but the client is updating the site in the future and needs a fool-proof solution.

    Thanks for the help.

    #11218
    Anh TranAnh Tran
    Keymaster

    Hi Juanita,

    You can overwrite the orderby parameter with this code:

    add_filter( 'posts_clauses', function( $clauses, $query ) {
        $relationship = $query->get( 'relationship' );
        if ( ! $relationship || 'REL_ID' != $relationship['id'] ) ) {
            return $clauses;
        }
        $clauses['orderby'] = 'ORDER BY post_date DESC';
        return $clauses;
    }, 99, 2 );

    It overwrites the orderby in the query. You might change it to fit your needs.

    #11270
    Content PilotContent Pilot
    Participant

    The function needs to be altered a little bit for anyone else looking to do the same thing. Only change was to remove ORDER BY in the new SQL statement.

    
    add_filter( 'posts_clauses', 'mb_sort', 99, 2 );
    /**
     * Sort just the POST relationship by date DESC.
     *
     * @param array $clauses Existing clauses.
     * @param WP_Query $query Main Query.
     * @return array
     */
    function mb_sort( $clauses, $query ) {
    
        $relationship = $query->get( 'relationship' );
        
        if ( ! $relationship || 'REL_ID' !== $relationship['id'] ) {
                return $clauses;
        }
        
        $clauses['orderby'] = 'post_date DESC';
        
        return $clauses;
        
    }
    
Viewing 3 posts - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.