1

I'm trying to do a custom query which is outside the scope of a single WP_Query, I think I should be using $wpdb but my SQL is a bit ropey. Also I only need the post IDs returned not post objects.

Basically I need to find all posts with a meta value of $foobar whose parent post has one or more specific terms. I.E:

GET all my_custom_post_type posts
IF their postmeta has a field my_custom_field with a value $foobar
AND their post_parent has the my_custom_tax terms foo & bar
RETURN the post's IDs as an array.

Any pointers would be great. Thanks!

2
  • 1
    Use a get_posts query for that Commented Aug 25, 2015 at 11:59
  • 1
    @PieterGoosen They're all custom post types so do use both post parents and taxonomies. Using get_posts I can't query the parent's taxonomy.
    – Jamie
    Commented Aug 25, 2015 at 12:09

1 Answer 1

4

You can still use get_posts:

$parents = get_posts(
    array(
        'posts_per_page' => -1,
        'post_type'      => 'my_custom_post_type',
        'fields'         => 'ids', // Just get IDs, not objects
        'tax_query'      => array(
            array(
                'taxonomy' => 'my_custom_tax',
                'field'    => 'slug',
                'terms'    => array(
                    'foo',
                    'bar',
                ),
            ),
        ),
    )
);

$post_ids = get_posts(
    array(
        'posts_per_page'  => -1,
        'post_parent__in' => $parents,
        'post_type'       => 'my_custom_post_type',
        'fields'          => 'ids',
        'meta_query'       => array(
            array(
                'key'   => 'my_custom_field',
                'value' => $foobar,
            ),
        ),
    )
);

Further reading on tax queries and meta queries.

2
  • Fantastic. Seems so obvious now! I guess I was overthinking it trying to wrap it up in a single query. Thank you.
    – Jamie
    Commented Aug 25, 2015 at 12:51
  • Hi @TheDeadMedic, im stuck with a problem. Would be very kind of you if you look into it. Thank you so much stackoverflow.com/q/66519311/9036446
    – evavienna
    Commented Mar 7, 2021 at 21:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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