create conditional priority in add_action

214 Views Asked by At

For a plugin, i am trying to set a different priorirty when adding an element to de admin menu bar. For administrators, it is another position then for all other user roles. I tried to define the priority as a variable in another function, return the correct priority based on the user role, and then insert this variable in the add_action statement. However, this keeps throwing errors. I assume because the add_action is earlier executed then the check for user roles.

So far I have the following:

set_priority() {
    $priority = 51;
    if (current_user_can('manage_options')){
    $priority = 21;
    }
    return $priority;
    }
add_action('init','set_priority');

And next:

function add_context_tab($wp_admin_bar) {

if(current_user_can('manage_options')){
    $url = network_site_url(). 'wp-admin/network/admin.php?page=content-page';
}
else{
    $url = network_site_url(). 'wp-admin/admin.php?page=content-page';
}

global $wp_admin_bar;

$wp_admin_bar->add_node( array(
    'id'    => 'content-page',
    'title' => '<span class="ab-icon dashicons dashicons-welcome-add-page"></span>' . __( 'Add content' ),
    'href'  => $url,
) );
}
$priority = set_priority();
add_action ('admin_bar_menu','add_context_tab',$priority);

I get an error: call to undefined function wp_get_user_roles I tried to change the priority from function set_priority that didnt work. I tried to include pluggable.php but get an error with undefined constant AUTH_COOKIE.

Any ideas?

1

There are 1 best solutions below

1
Moshe Gross On

Perhaps putting the add_action('admin_bar_menu','add_context_tab',$priority) in the set_priority() function would work

set_priority() {
    $priority = 51;
    if (current_user_can('manage_options')){
        $priority = 21;
    } 
    add_action('admin_bar_menu','add_context_tab',$priority)
}
add_action('init','set_priority');