• I am pulling my hair out trying to achieve a query to get post id’s for the posts which are in a certain category id array, but not in another category id array.

    For some reason the SQL request uses wrong id’s..different than the ones I insert.

    Here’s my code:

    $notInCategories = array('103','106','132','102','10','57','58','28','48');
    
    			$args = array(
    					'post_type' => 'post',
    					'post_status' => 'publish',
    					'order_by' => 'ID',
    					'tax_query' => array(
            			'relation' => 'AND',
    							 0 => array(
    									'taxonomy' => 'category',
    									'field'    => 'id',
    									'terms'    => array(10,11,12)
    							),
    							1 => array(
    									'taxonomy' => 'category',
    									'field'    => 'id',
    									'terms'    => $notInCategories,
    									'operator' => 'NOT IN',
    							)
    					),
    					'meta_query' => array(
           					'relation' => 'AND',
    								array(
    								 'key' => 'joke_type',
    								 'value' => $type,
    								 'type' => 'CHAR',
    								 'compare' =>  '='
    							 ),
    								 array(
    									 'key' => 'joke_rating',
    									 'value' => 3,
    									 'type' => 'SIGNED',
    									 'compare' => '>='
    								 )
    					 )
    			);
    			$myquery = new WP_Query( $args );
    			echo '<p>REQUEST:'.$myquery->request.'</p>';

    Here’s what it outputs:
    REQUEST:SELECT SQL_CALC_FOUND_ROWS wp_njkf_posts.ID FROM wp_njkf_posts INNER JOIN wp_njkf_term_relationships ON (wp_njkf_posts.ID = wp_njkf_term_relationships.object_id) INNER JOIN wp_njkf_postmeta ON ( wp_njkf_posts.ID = wp_njkf_postmeta.post_id ) INNER JOIN wp_njkf_postmeta AS mt1 ON ( wp_njkf_posts.ID = mt1.post_id ) WHERE 1=1 AND ( wp_njkf_term_relationships.term_taxonomy_id IN (11,12,13) AND wp_njkf_posts.ID NOT IN ( SELECT object_id FROM wp_njkf_term_relationships WHERE term_taxonomy_id IN (11,30,50,59,60,104,105,108,134) ) ) AND wp_njkf_posts.post_type = 'post' AND ((wp_njkf_posts.post_status = 'publish')) AND ( ( wp_njkf_postmeta.meta_key = 'joke_type' AND CAST(wp_njkf_postmeta.meta_value AS CHAR) = 'joke' ) AND ( mt1.meta_key = 'joke_rating' AND CAST(mt1.meta_value AS SIGNED) >= '3' ) ) GROUP BY wp_njkf_posts.ID ORDER BY wp_njkf_posts.post_date DESC LIMIT 0, 10

    I can’t figure out WHY IN GOD’S NAME this happens..

    Any ideas?

Viewing 1 replies (of 1 total)
  • Thread Starter andreeaButiu

    (@andreeabutiu)

    I realized why the values are different. It’s because term_taxonomy_id is the connection between the category id (which is term_id from the table term_taxonomy) and the post (which is object_id in term_relationship), so it is different than category id.

    What I don’t understand still is why posts from those excluded categories still appear.

Viewing 1 replies (of 1 total)
  • The topic ‘Custom WP_Query to pull posts IN category array, but NOT IN category array’ is closed to new replies.