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

This topic contains 2 replies, has 2 voices, and was last updated by  Clayton Collie 9 months, 2 weeks ago.

  • Creator
    Topic
  • #11199
    Resolved
    Clayton Collie
    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.

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

    Anh 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

    Clayton Collie
    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 2 replies - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.