Delete Current Author Frontend user while delete custom post type

I created custom post type using Toolset. I want to delete current post author ( front-end user ) when i delete the post.

I tried below code :

add_action('before_delete_post', 'my_deleted_post');
function my_deleted_post($post_id){
    global $post; 
    if ($post->post_type == "agency") {
        //echo $post->post_author;exit;
        require_once(ABSPATH.'wp-admin/includes/user.php' );
        wp_delete_user( intval($post->post_author) );
    }
}

But it is not working to me can anyone help me here ?

1 Answer
1

I don’t think $post will be defined where you are using it. Try relying on the post ID that is passed to your function instead:

add_action('before_delete_post', 'my_deleted_post');

function my_deleted_post($post_id){ 
    if ( "agency" == get_post_type( $post_id ) ) {
        require_once(ABSPATH.'wp-admin/includes/user.php' );
        wp_delete_user( intval( get_post_field( 'post_author', $post_id ) ) );
    }
}

Be aware that wp_delete_user() will try to delete any other posts, of any post type, owned by the same user and that might cause an infinite recursive loop. Using the third parameter to wp_delete_user to reassign other posts may be a good idea. Or simply remove your function from the hook before trying to delete the user:

add_action('before_delete_post', 'my_deleted_post');

function my_deleted_post($post_id){ 
    if ( "agency" == get_post_type( $post_id ) ) {
        remove_action('before_delete_post', 'my_deleted_post');
        // break unwanted recursion
        require_once(ABSPATH.'wp-admin/includes/user.php' );
        wp_delete_user( intval( get_post_field( 'post_author', $post_id ) ) );
    }
}

Leave a Comment