2

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 ?

4
  • Where is your code saved (which file)? Why are you including user.php? Sep 20, 2016 at 11:58
  • inside function.php Sep 20, 2016 at 12:02
  • Using an action or filter hook or just as it is? Sep 20, 2016 at 12:03
  • I updated my question.... Sep 20, 2016 at 12:06

1 Answer 1

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 ) ) );
    }
}
6
  • I got ERR_EMPTY_RESPONSE so it goes to infinite loop. Sep 20, 2016 at 12:52
  • Removing the hooked function should fix that - question edited. Sep 20, 2016 at 12:57
  • Yes it is reducing the infinite loop... Thanks For The Help... Sep 20, 2016 at 14:06
  • Cool - no problem! Sep 20, 2016 at 14:06
  • Just One Editing in answer that use wp_redirect('your desire path'); so it wil not display message access denied Sep 20, 2016 at 14:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.