I am trying to delete a post based on a custom field value called randomid.

 $querystr = "
    DELETE FROM $wpdb->posts LEFT JOIN $wpdb->postmeta
    WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id 
    AND $wpdb->postmeta.meta_key = 'randomID' 
    AND $wpdb->postmeta.meta_value = '$randomID'";

Which gives me something like

DELETE FROM wp_posts  LEFT JOIN wp_postmeta WHERE wp_posts.ID = wp_postmeta.post_id AND wp_postmeta.meta_key = 'randomID' AND wp_postmeta.meta_value = '070313wIOLTxv';

But i get a mysql syntax error, what am i doing wrong?

1 Answer 1


You don't have a ON for your LEFT JOIN, I guess the WHERE statement you use has to be the ON statement.

You should use this query instead:

$querystr = "
  DELETE FROM $wpdb->posts
  LEFT JOIN $wpdb->postmeta ON $wpdb->postmeta.post_id = $wpdb->posts.ID
  WHERE $wpdb->postmeta.meta_key = 'randomID'
  AND $wpdb->postmeta.meta_value = '$randomID'";

Reference here: http://dev.mysql.com/doc/refman/5.0/en/join.html

  • ah totally overlooked the ON. unfortunatly the new $querystr still doesn't work. #1064 - You have an error in your SQL syntax;........use near 'LEFT JOIN wp_postmeta ON wp_postmeta.post_id = wp_posts.ID WHERE....
    – alex
    Commented Jun 11, 2013 at 8:46
  • 1
    Based on this webpage you could try to change the DELETE FROM rule to DELETE $wpdb->posts.* FROM $wpdb->posts? Commented Jun 11, 2013 at 8:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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