0
votes

I have the current SQL query which will delete all posts from a custom post type clothing which are older than 2 days

    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

The problem is that this query doesn't seem to delete the related metas such as related custom fields of the deleted posts.

My question is, how can I modify this code to also delete the relate metas from those posts?

Thanks

1
is there a reason for not defining foreign key constraint ? - SMA
I have no idea unfortunately, I didn't write this query, I found it on another thread and tested it to be working, but it just doesn't delete the related metadata - user2028856
I think DELETE FROM does not work this way. Try putting the query in some tool like phpMyAdmin. To be sure it will pass you can make three queries for the purpose. One to select post IDs for removal. Second DELETE FORM pm where post_id IN previously selected IDs and the last to delete posts where ID in the same selected IDs. - Rolice

1 Answers

-1
votes

You should process in two steps :

1- with you query, build an array of posts to delete 2- loop this array with foreach and wp_delete_post()

(http://codex.wordpress.org/Function_Reference/wp_delete_post)

The core function wp_delete_post will take care of all related data, like metas, but also counts of posts in terms, wich are stored in the database and modified on insert or deletion of posts