Get post id in wordpress action?

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?

Read More

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

Related posts

Leave a Reply

2 comments

  1. 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
    }
    
  2. 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!