Wordpress使用wpdb查询删除不在特定类别中的帖子

时间:2018-10-15 14:48:01

标签: php sql wordpress

如何修改以下查询以删除所有自定义帖子类型“列表”不在特定Wordpress类别中的帖子?

请注意,在特殊情况下,我必须使用$wpdb->query()。 我要排除的类别是术语ID的21、22和24。

$wpdb->query('DELETE FROM wp_posts WHERE post_type = "listings"');

更新-此查询使我更接近所要查询的内容,但会引发SQL错误。

DELETE FROM wp_posts a 
LEFT JOIN wp_term_relationships b ON ( a.ID = b.object_id ) 
LEFT JOIN wp_postmeta c ON ( a.ID = c.post_id ) 
LEFT JOIN wp_term_taxonomy d ON ( d.term_taxonomy_id = b.term_taxonomy_id ) 
LEFT JOIN wp_terms e ON ( e.term_id = d.term_id ) 
WHERE a.post_type = "listings" 
AND e.term_id NOT IN (21,22,24);

错误:

WordPress database error You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LEFT JOIN wp_term_relationships ON wp_posts.ID = wp_term_relationships.object_id' at line 1 for query DELETE FROM wp_posts LEFT JOIN wp_term_relationships ON wp_posts.ID = wp_term_relationships.object_id LEFT JOIN wp_postmeta ON wp_posts.ID = wp_postmeta.post_id LEFT JOIN wp_term_taxonomy ON wp_term_taxonomy.term_taxonomy_id = wp_term_relationships.term_taxonomy_id LEFT JOIN wp_terms ON wp_terms.term_id = wp_term_taxonomy.term_id WHERE wp_posts.post_type = "listings" AND wp_terms.term_id NOT IN (21,22,24)

1 个答案:

答案 0 :(得分:1)

$wpdb->query('DELETE wp_posts FROM wp_posts 
INNER JOIN wp_term_relationships ON wp_posts.id = wp_term_relationships.object_id
INNER JOIN wp_term_taxonomy ON wp_term_relationships.object_id = wp_term_taxonomy.term_taxonomy_id
WHERE wp_posts.post_type = "listings" AND wp_term_taxonomy.taxonomy NOT IN (taxonomy_1_slug, taxonomy_2_slug, etc.)');