Mysql – How to filter posts with multiple category names in WordPress

databaseMySQLWordpress

I am trying to work around a plugin for Word Press called "Event Calendar 3". This plugin lets you create events and then feeds them into a SQL table in the WordPress database. However, this plugin does not discriminate between different types of events, eg repeating events, one-off events.

The beginning of my solution was to create a category called "Repeating Event", and when I created an Event post, also tagged it Repeating Event. I then tried to structure a query that would return posts that were categorized "Events," but would also exclude "Repeating Events."

$query = SELECT *
         FROM wp_posts p, wp_ec3_schedule s, wp_terms ts, wp_term_taxonomy t, wp_term_relationships r
WHERE p.ID = s.post_ID
AND r.term_taxonomy_id = t.term_taxonomy_id
AND ts.term_id = t.term_id
AND name != "Repeating"

The trouble is, posts that have the category "Repeating" also have the category "Events" (they have to in order to show up in the calendar). So the posts that have the category "Repeating" still show up because their category 'name' is not just "Repeating," it's "Events" as well!

The WordPress function query_post() doesn't help because not only do I have to filter by category (which query_post() does), but I also need to be able to specify that the rows returned by the query are only those that have a start date after today (there is a column in the wp_ec3_schedule table called 'start' that lists the start time of the event).

Any suggestions?

Thx.

Best Answer

Not sure that I understand everything, but take a look at this example. This lists post_id of posts on my site which are in category how-to, but are not in categories database and code.

SELECT  `object_id` AS PostID
FROM    `wp_term_relationships` AS r
        JOIN `wp_term_taxonomy` AS x ON x.`term_taxonomy_id` = r.`term_taxonomy_id`
        JOIN `wp_terms` AS t ON t.`term_id` = x.`term_id`
WHERE   x.`taxonomy` = 'category'
        AND `slug` = 'how-to'
        AND `object_id` NOT IN
           (
            SELECT `object_id`
            FROM `wp_term_relationships` AS r
            JOIN `wp_term_taxonomy` AS x ON x.`term_taxonomy_id` = r.`term_taxonomy_id`
            JOIN `wp_terms` AS t ON t.`term_id` = x.`term_id`
            WHERE   x.`taxonomy` = 'category'
            AND `slug` IN  ( 'database', 'code' )
            );
Related Topic