Support

Account

Home Forums General Issues Getting Field Value of A Different CPT through Relationship with WP_Query

Solving

Getting Field Value of A Different CPT through Relationship with WP_Query

  • I am having such a hard time trying to figure out how to do this. Here is my situation:

    Vendor CPT
    – Sponsored: no / yes

    Solution CPT
    – Relationship: Vendor object

    I am trying to list all Solutions, but orderby whether or not they are connected to a sponsored vendor. I need all sponsored solutions showing first.

    For the life of me, I cannot construct a WP_Query that is able to traverse that relationship and get the correct value.

  • function solution_directory( $query ) {
    	
    	if ( $query->is_main_query() && !$query->is_feed() && !is_admin() && $query->is_post_type_archive( 'solution' ) ) {
    		
    		$meta_query = array(
    			array(
    				'key' => 'sponsored',
    				'value' => 'yes',
    				'compare' => 'IN'
    			)
    		);
    		
    		$query->set( 'meta_query', $meta_query );
    		$query->set( 'orderby', 'meta_value' );
    		$query->set( 'meta_key', 'sponsored' );
    		$query->set( 'order', 'ASC' );
    		$query->set( 'posts_per_page', '4' );
    		
    		$query->set( 'facetwp', 'true' );
    		
    	}
    
    }
    add_action( 'pre_get_posts', 'solution_directory' );

    I’m trying this sort of thing, but I know that I’m not reaching the sponsored field through the relationship with this.

  • You cannot to want to do. You cannot query or order posts by a relationship field or by a value of the related post.

    In order query by this value you need to copy the value to the post(s) that you need to use it for. You can do this using an acf/save_post filter that runs when saving post type “solution”, get the value from the related “vendor” and store it in the meta table attached to the “solution”

    Another possibility is to query vendors to get a list of sponsored vendors and then somehow alter the solution query using the list of posts returned.

    Sorry, I don’t have example code for doing either.

  • That’s what I was afraid of.

    What about using a bidirectional field for ‘sponsored’ … would that work?

  • No, because what you want to query/sort by is still not part of the posts you want to query/sort. This is a limitation of using WP_Query and the way the WP database is built.

Viewing 5 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic.