0

I'm working on a project have 2 CPTs:

  • Projects
  • Units

Every Unit has a meta value containining the id of Project
Every Project is assigned a custom taxonomy named Regions

Now I need get all Units in a specific Region

I think I must WP_Query to get all Projects in a Region then use the array of Projects ids to find Units by another WP_Query. I've tried a few times but was unable to solve it. How can I get all Units in a Region?

0

You're correct in your approach. If you post your code will be better, but something like this:

$args = array(
    'post_type' => 'project',
    'tax_query' => array(
        array(
            'taxonomy' => 'region',
            'field'    => 'slug',
            'terms'    => $region, //set your region
        ),
    ),
);
$the_query = new WP_Query( $args );

// The Loop of Projects by Region
if ( $the_query->have_posts() ) {

    $projectsid = array();
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        $projectsid[] = get_the_ID();
    }

    $args = array(
        'post_type' => 'unit',
        'meta_query' => array(
            array(
                'key'       => $keyname, //set the key name which store ID
                'value'     => $projectsid,
                'compare'   => 'IN',
                'type'      => 'NUMERIC'
            ),
        ),
    );
    $the_query = new WP_Query( $args );

    // The Loop of units in project per region
    if ( $the_query->have_posts() ) {

        while ( $the_query->have_posts() ) {
            $the_query->the_post();
            //do something

        }

    } else {

        //No units for projects in this region

    }

} else {

    //No projects in this region

}

wp_reset_query();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.