Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm in the middle of doing some fairly complex queries involving metadata from a custom post type. Unfortunately if any posts are deleted the metadata stays put which complicates matters as I am counting it.

I was wondering how best to go about deleting the orphan metadata in the event that the post is deleted.

Should I include a function that deletes them the database through $wpdb?

I found an SQL query that does just that but I'm not sure how to format it.

DELETE pm
FROM wp_postmeta pm
LEFT JOIN wp_posts wp ON wp.ID = pm.post_id
WHERE wp.ID IS NULL

I tried it in phpmyadmin on a backup copy of my database but to no avail.

share|improve this question

1 Answer 1

up vote 0 down vote accepted

This snippet is good enough, use it with $wpdb. In this case I would use :

<?php
add_action( 'before_delete_post', 'my_func' );
function my_func( $postid ){

// We check if the global post type isn't ours and just return
global $post_type;   
if ( $post_type != 'my_custom_post_type' ) return;

// My custom stuff for deleting my custom post type here
}
?>

Source

share|improve this answer
    
Perfect! Works beautifully. Thank you. –  mantis Jun 19 '13 at 6:35

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.