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 want to delete post id form my custom table, when deleting a post. I have tried this way, nothing happened. Please help.

add_action('delete_post', 'delete_data');

function delete_data($post_id) {
   global $wpdb;
   $table_name = $wpdb->prefix . 'post_order';
   if ($wpdb->get_var($wpdb->prepare("SELECT `id` FROM $table_name WHERE `pid` = %d", $post_id))) {
       $wpdb->query($wpdb->prepare("DELETE FROM $table_name WHERE `pid` = %d", $post_id));
share|improve this question

delete_post fires when the post is deleted permanently, not when it is trashed. I don't know if that is relevant but keep that in mind. That is the only real WordPress specific part of this question. The rest is bad PHP.

Variables do not expand inside single quotes. You are a sending a query to the database that literally looks like

SELECT `id` FROM $table_name WHERE `pid` = XxX

What you want is either

$wpdb->prepare('SELECT `id` FROM '.$table_name.' WHERE `pid` = %d', $post_id)


$wpdb->prepare("SELECT `id` FROM {$table_name} WHERE `pid` = %d", $post_id)

To run the function when you trash the post, you probably want the one or more of the status transition hooks. But a word or caution: if you delete from your table on post "trash" you can't reverse it. The "restore" function will fail to work correctly on these posts.

share|improve this answer
Yes bro, you got my problem. When i clear trash, delete_ post fires and delete operation succeed for my table. But I want to delete post id immediately from my db table when deleting the post. Thrash is not my headache.And i am aware about single quote & double quote :). It was a typo mistake – Shakil May 6 '13 at 18:43

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.