Question

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.

Was it helpful?

Solution

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
     )
);
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top