Custom Fields
Support MB Relationships Filter the orderby of entries retrieved from database

  • Creator
  • #11199
    Resolved Content Pilot

    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.

Viewing 2 replies - 1 through 2 (of 2 total)
  • Author
  • #11218
    Anh Tran

    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.

    Content Pilot

    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 2 replies - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.