I am trying to add an error notice to an admin screen. Like this. So. I have a the function which outputs the error:
public function my_error_notice()
{
$text = __( 'There has been an error. Error!', 'kea' );
$output = <<<EOT
<div class="error notice">
<p>$text</p>
</div>
EOT;
}
And, in the constructor for my plugin I have:
add_action( 'admin_notices', array($this, 'my_error_notice' ));
This works and outputs the error message. But - I only want this error message to appear when a specific condition occurs. See below:
I am hooking into user_register and in my callback for that I am doing some extra database work. I have a logged in author. That author has been given the capability to add/register new users. They do this using the normal WP admin screen for an admin to add a new user. In my plugin I have;
add_action('user_register', array($this, 'link_user_to_tutor'));
and
public function link_user_to_tutor($new_user_id)
{
global $current_user;
$current_user_roles = $current_user->roles;
$current_user_id = get_current_user_id();
if (($current_user_id !== 0) && in_array('author', $current_user_roles))
{
error_log("non admin user adding" . $new_user_id);
//int or false
$result = $this->wpdb->insert($this->kea_table_name4, array(
'tutor_idx' => $current_user_id,
'student_id' => $new_user_id
), array( '%d', '%d'));
}
if ($result === false)
{
$err = "link_user_to_tutor-" . $new_user_id . "-" . $current_user_id . " wp user was created but not linked to tutor";
$this->mail_error($err);
error_log($err);
//I want to print a message to the author/admin here to say that adding the new user has not worked.
}
}
Thanks
user-new.php
is passing along that failure as a URL argument in the redirect URL. Although looking at your code it doesn't actually prevent the addition of the user. I'd also move that lastif
condition inside the first as$result
only exists if the first condition is true, you'll get a PHP warning otherwise. This is also something custom capabilities is meant forif ( current_user_can( 'link_tutor' )..
etc