How to exclude certain category in SQL Statement

Here’s my current codes to get popular post from wordpress wp_post table. How can I exclude those in categories such as 3 or 4?

$popularposts = "SELECT ID,post_title FROM {$wpdb->prefix}posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY comment_count DESC LIMIT 0,".$pop_posts;
$posts = $wpdb->get_results($popularposts);

Related posts

Leave a Reply

2 comments

  1. Dugg through the web and stackoverflow, almost solved the problem. Still I need add

    ORDER BY comment_count DESC LIMIT 0,".$pop_posts
    

    somewhere in the following code.

    $popularposts  = "SELECT * FROM $wpdb->posts 
    INNER JOIN $wpdb->term_relationships ON($wpdb->posts.ID = $wpdb->term_relationships.object_id)  
    INNER JOIN $wpdb->term_taxonomy ON($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)  
    
    WHERE ($wpdb->term_taxonomy.term_id <> 3  
       AND $wpdb->term_taxonomy.term_id <> 4  
       AND $wpdb->term_taxonomy.taxonomy = 'category'   
       AND $wpdb->posts.post_type = 'post'  
       AND $wpdb->posts.post_status = 'publish')";
    
  2. after ‘publish’ you add (assuming the field for categorie is categorie)

    and categorie not in ('3', '4')
    

    or, if categorie is numeric:

    and (categorie < 3 or categeorie > 4)