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
delete_post_meta( int $post_id, string $meta_key, mixed $meta_value = '' ): bool. Deletes a post meta field for the given post ID.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With