Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress SQL Delete Custom Post Types and Meta

I have the following SQL query which is able to fetch and delete all of the posts of a custom post type that is older than X days.

SELECT * FROM `wp_posts`
WHERE `post_type` = ‘clothing’
AND DATEDIFF(NOW(), `post_date`) > 2

DELETE * FROM `wp_posts`
WHERE `post_type` = ‘clothing’
AND DATEDIFF(NOW(), `post_date`) > 2

However from what I've read online, it seems that the code above doesn't really delete the posts's meta information, so I'll still have a bunch of left over data.

My question is, how can I modify this code so that all of the related meta information is also removed from the deleted posts?

Thanks

like image 876
user2028856 Avatar asked Nov 18 '14 11:11

user2028856


People also ask

How do I remove post and Meta from Wordpress?

delete_post_meta( int $post_id, string $meta_key, mixed $meta_value = '' ): bool. Deletes a post meta field for the given post ID.

Where are custom post types stored in Wordpress?

The wp_posts table stores all of the content of your posts, of all post types. So it doesn't matter if we're talking about a blog post, a page, a revision, an attachment, or a custom post type: they'll all be stored in this wp_posts table.


1 Answers

You can delete the data by joining the tables. In WP wp_posts and wp_postmeta are related with post_id in the wp_postmeta table. Using the query below it will delete from both tables. However there are other options as well i.e you can fire a trigger after delete on wp_posts to delete the data from the related table or a foreign key constraint with on delete cascade

delete
p,pm
from wp_posts p
join wp_postmeta pm on pm.post_id = p.id
where p.post_type = 'clothing'
and DATEDIFF(NOW(), p.post_date) > 2
like image 152
Abhik Chakraborty Avatar answered Sep 28 '22 04:09

Abhik Chakraborty