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

add_action( 'delete_post', 'my_delete_function' );
 function my_delete_function() { 
   global $wpdb;
   $wpdb->query("
    DELETE FROM wp_votes WHERE post=".$thePostID."
;);
 }

How can I get the id of the post being deleted?

Additionally, will this still work if multiple posts are deleted in the admin?

share|improve this question

2 Answers 2

up vote 0 down vote accepted

I haven't tested so I'm providing you with two possibilities, Inside a loop, use the following:

$post_id = get_the_ID();

Outside a loop, use the following:

global $wp_query;
$post_id = $wp_query->post->ID;

Or:

global $post;
$post_id = $post->ID

Or you can pass the post ID in a function, much like

function my_function($post_id){
    // code
}
share|improve this answer
    
Inside the loop, it is probably best to use get_the_ID() –  v0idless Jan 8 '12 at 16:15
    
Good point. I edited my answer. Thank you :) –  Asko Jan 8 '12 at 16:22
    
There's no reason whatsoever to use a solution other than the one passed as a function parameter - all others are void and risk breaking! –  TheDeadMedic Jan 8 '12 at 16:31

Add a parameter to your function, which will be passed the ID of the current post being deleted.

add_action( 'delete_post', 'my_delete_function' );
function my_delete_function( $post_id /* <- ID of post being deleted */ )
{ 
    global $wpdb;
    $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->prefix}_votes WHERE post = %d", $post_id ) );
}

Using any external variable (like a global in @Asko's answer) removes any guarantee that the post actually being deleted is the one you're working on within your function - it could either fail completely, or even delete data for the wrong post!

share|improve this answer

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.