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?


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

| improve this answer | |
  • 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 Jun 11 '13 at 8:46
  • 1
    Based on this webpage you could try to change the DELETE FROM rule to DELETE $wpdb->posts.* FROM $wpdb->posts? – Mike Madern Jun 11 '13 at 8:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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