0
votes

I have one array with the term_id.

$termID = array(165,166,158,157);

I want get ID of posts that they have all elements this array.(Get all posts that they are in the all categories with term_id 165,166,158,157). Name of my category is newcat.

I wrote :

SELECT r.object_id
FROM wp_term_relationships r 
LEFT JOIN wp_term_taxonomy t ON r.term_taxonomy_id = t.term_taxonomy_id
WHERE t.term_id IN (165,166,158,157)
GROUP BY r.object_id

but I get object_id that they have one or more elements of this array.

2

2 Answers

0
votes

You can use get_posts instead of manual sql query :

$post_ids = get_posts(array(
    'numberposts'   => -1, // get all posts.
    'tax_query'     => array(
        array(
            'taxonomy'  => 'category',
            'field'     => 'id',
            'terms'     => array(165,166,158,157),
        ),
    ),
    'fields'        => 'ids', // Only get post IDs
));

haven't tried this yet but give it a try :

$post_ids = get_posts(array(
        'numberposts'   => -1, // get all posts.
        'relation'  =>    'AND'
        'tax_query'     => array(
            array(
                'taxonomy'  => 'category',
                'field'     => 'id',
                'terms'     => array(165),
            ),
             array(
                'taxonomy'  => 'category',
                'field'     => 'id',
                'terms'     => array(166),
            ),
             array(
                'taxonomy'  => 'category',
                'field'     => 'id',
                'terms'     => array(158),
            ),
             array(
                'taxonomy'  => 'category',
                'field'     => 'id',
                'terms'     => array(157),
            ),
        ),
        'fields'        => 'ids', // Only get post IDs
    ));

http://codex.wordpress.org/Template_Tags/get_posts

Cheers!

0
votes

I guess you are looking for a way to query this to your database? If so:

SELECT * FROM categories WHERE newcat IN(165,166,158,157)

I'm not very expirienced in WP, but you'll catch the drift.