Before Delete Post

I am trying to update the value of one custom post type’s meta when another custom post type is deleted.

When a space_rental is deleted, I need to update some meta value on a space.

I don’t think I can use delete_post because it fires after the meta data has been deleted, but this isn’t working for me either (either on trashing the post or emptying the trash).

Here is the function and below that is the structure of the meta data for each post type.

//When a space_rental is deleted, we release the space slots they had saved
add_action( 'before_delete_post', 'tps_delete_space_rental' );
function tps_delete_space_rental( $postid ){

if (get_post_type($postid) != 'space_rental') {
return;
}
//Loop through the selected slots in the rental
$selectedSlots = get_post_meta($postid, 'selectedSlots', true);
foreach ($selectedSlots as $slot) {
    $spaceSlots = get_post_meta($slot['spaceid'], 'allSlots', true);
    //Loop through the slots in the space and find the ones that have the rentalID set to the deleted post
    foreach ($spaceSlots as $sSlot) {
        if($postid == $sSlot['details']['rentalID']) {
            $sSlot['details']['slotStatus'] = 'open';
        }
    }
}
}

The ‘space’ post_type meta is stored like this:

allSlots => array(
'timestamp' => '123456789', //timestamp representing this slot
'details' => array(
    'slotStatus' => 'open', //this is either open or filled
    'slotUser' => 123, //The ID of the user who owns the rental using this slot
    'rentalID' => 345, //The post_id of the 'space_rental' that is using this slot
),
);

This ‘space_rental’ post_type meta is stored like this:

selectedSlots => array(
'spaceSlots' => array(
    123456789, 654321987, 9876432654, etc...,// An array of timestamps in this rental
),
    'spaceid' => 789, //The post_id of the 'space' where this rental is
);

2 Answers
2

There’s a trash post hook

add_action( 'trash_post', 'my_func' );
function my_func( $postid ){

    // We check if the global post type isn't ours and just return
    global $post_type;   
    if ( $post_type != 'my_custom_post_type' ) return;

    // My custom stuff for deleting my custom post type here
}

Leave a Comment