WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

FROM wp_postmeta pm
LEFT JOIN wp_posts wp ON wp.ID = pm.post_id

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

share|improve this question
up vote 0 down vote accepted

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

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


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

Your Answer


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.