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!

  • 1
    Use a get_posts query for that – Pieter Goosen Aug 25 '15 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 Aug 25 '15 at 12:09
2

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.

  • Fantastic. Seems so obvious now! I guess I was overthinking it trying to wrap it up in a single query. Thank you. – Jamie Aug 25 '15 at 12:51

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.