Support

Account

Home Forums General Issues Filter posts by custom fields of the related posts ?

Helping

Filter posts by custom fields of the related posts ?

  • I have two post types named ‘programs’ and ‘universities’, where different programs are connected with different universities.

    I want to filter these programs with custom fields of their related universities, such as university’s ranking or location.

    I can filter my programs with their own custom fields or taxonomies using WP_Query arguments. However, I want to filter them with their related university’s custom fields.

    I went through the complete documentation but couldn’t find a solution.

  • Here’s what I’ve done so far:

    <?php
    //filter by custom field
    if(isset($_GET['shift']))
    	$args['meta_query'][] = array(
    		'key' => 'shift',
    		'value' => $shift,
    		'compare' => 'LIKE'
    	);
    
    //filtered by taxonomy
    if(isset($terms1))
        $args['tax_query'][] = array(
        	'taxonomy' => 'category',
        	'field' => 'slug',
        	'terms' => $terms1,
        	'operator' => 'IN',
    
    // Don't know how to filter by related post's custom fields
    
    $proSearch_query = new WP_Query($args);
    while ($proSearch_query->have_posts()){
    	$proSearch_query->the_post();
    
    			$result[] = array(
    			"id" => get_the_ID(),
    				"title" => get_the_title(),
    				"rel_university" => get_field('uni')[0]->post_name,
    				//returns related post's custom field:
    				"ranking" => get_field('university')[0]->ranking,
    			);
    }
    echo json_encode($result);
    die(); 
    ?>
    
Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘Filter posts by custom fields of the related posts ?’ is closed to new replies.