Support MB Relationships pre_get_posts to get all posts connected to single object Reply To: pre_get_posts to get all posts connected to single object

#11694
Content PilotContent Pilot
Participant

I disabled every plugin and reverted to default WP theme to test. I am still stumped. Have a look at the two screenshots. First one is the base query where the query and query_vars match. This query assigns the post type to every other function to get things like post type archive title, etc.
basic query

Second is when the query_vars are used to alter the query. Notice how the query and query vars are different. The filtering of posts works great to show only the post that is related to 2735.
altered query

Can you add this code to your install and let me know if you are seeing the same errors?


add_action( 'parse_query', 'poa_filter_query_by_relationship', 10, 1 );
/**
 * Filter the main query by using URL parameters
 * 
 * @param object $query WP_Query.
 * @return object
 * 
 * @since 3.6.8
 */

function poa_filter_query_by_relationship( $query ) {
    
    $id     = get_query_var('relation_id');
    $from   = get_query_var('relation_from');
    $to     = get_query_var('relation_to');
    
    if ( ! empty( $id ) && ! is_admin() && $query->is_main_query() ) {

        if ( ! empty( $from ) ) {
            
            $query->set( 'relationship', 
                array( 
                    'id'  => esc_attr( $id ),
                    'from'    => intval( $from ),
                )
            );

            var_dump($query);

        } elseif ( empty( $to ) ) {

            $query->set( 'relationship', 
                array( 
                    'id'  => esc_attr( $id ),
                    'to'  => intval( $to )
                )
            );
        }
        
    }

}

add_filter( 'query_vars', 'add_query_vars' );
/**
     * Add query vars to build query with URL parameters
     *
     * @param array $vars WP_Query variables.
     * @return array
     * @since 3.6.8
     */
    public function add_query_vars( array $vars ) {
        $vars[] = 'relation_id';
        $vars[] = 'relation_from';
        $vars[] = 'relation_to';
        return $vars;
    }