4

My site has custom post type 'Portfolio'. If a user has at least one Portfolio, how can I disable the option to delete that user?

I found the action/hook delete_user, but it doesn't seem right for this issue.

2

When you click on "delete", the action 'delete_user' will be launched: https://core.trac.wordpress.org/browser/tags/4.4.1/src/wp-admin/includes/user.php#L313

After that you can check, if the user has written at least one 'portfolio' post.

add_action('delete_user', 'sw_portfolio_check');

function sw_portfolio_check( $user_id ) {
    $result = new WP_Query(
                array(
                    'author'=>$user_id,
                    'post_type'=>'portfolio',
                    'posts_per_page'=>1,
                )
            );
    if ( count($result->posts) !== 0 ){
        wp_die("User has a portfolio and can't be deleted");
    }
}
3

You want to disable the option to delete, If you mean the delete button on the user list at /wp-admin/users.php you can use user_row_actions class to hide the 'delete' link with below snippet:

add_filter(
  'user_row_actions',
  function($actions, $user_object) {
    $result = new WP_Query(
                array(
                    'author'=> $user_object->ID,
                    'post_type'=>'portfolio',
                    'posts_per_page'=>1,
                )
            );
    if ( count($result->posts) !== 0 ){
      unset($actions['delete']);
    }
    return $actions;
  },
  1,2
);

The above snippet just hides the link. It does not prevent access to the delete screen. To do that, we'll need more code:

add_action(
  'load-users.php',
  function() {
    if (isset($_GET['user'])) {
      $user_object = get_userdata($_GET['user']);
          $result = new WP_Query(
                        array(
                            'author'=> $user_object->ID,
                            'post_type'=>'portfolio',
                            'posts_per_page'=>1,
                        )
                    );
        if( count($result->posts) !== 0 ){
        wp_die('This user cannot be deleted');
        }
    }
  }  
);

Hope this help you well!

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.