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 have this code to remove orphaned posts after deleting custom post type.

It works, but this code...

global $wpdb;
$wpdb->query( 
    $wpdb->prepare( 
    "DELETE a,b,c FROM wp_posts a
    LEFT JOIN wp_term_relationships b ON (a.ID=b.object_id)
    LEFT JOIN wp_postmeta c ON (a.ID=c.post_id)
    WHERE a.post_type='attorneys'"
  )
);

...is throwing this error:

PHP Notice: wpdb::prepare was called incorrectly. The query argument of wpdb::prepare() must have a placeholder.

So, after reading the explanation on make.wordpress.org by Andrew Nacin, I (sorta) gather that ...well.. I'm missing the second argument.

Then after reading this stack post, I'm wondering if I even need the prepare() function. Are there any variables holding unknown values? I'm not clear on this.

...what am I missing?

UPDATE: This code also works, but w/o the prepare() I wonder if its safe.

global $wpdb;
$wpdb->query( 
  "DELETE a,b,c FROM wp_posts a
  LEFT JOIN wp_term_relationships b ON (a.ID=b.object_id)
  LEFT JOIN wp_postmeta c ON (a.ID=c.post_id)
  WHERE a.post_type='attorneys'"
);

Please advise.

share|improve this question

1 Answer 1

up vote 4 down vote accepted

It's always advised to use $wpdb->prepare when you are taking input from user. This will help in protecting queries against SQL Injection. For more details, check the Codex

When you use $wpdb->prepare, you must pass the variables to the query. In your case, you can skip using $wpdb->prepare as you are using a hard coded value. But if you have the same value in terms of a variable, you need to modify it as below

$post_type = 'attorneys';

$wpdb->query( 
     $wpdb->prepare(
          "DELETE a,b,c FROM wp_posts a
          LEFT JOIN wp_term_relationships b ON (a.ID=b.object_id)
          LEFT JOIN wp_postmeta c ON (a.ID=c.post_id)
          WHERE a.post_type=%s",
          $post_type
     )
);
share|improve this answer
    
Cool. Thanks for explanation. I get it now. –  sleeper Jun 16 at 14:38

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.