How to remove nodes site wide from the toolbar on multisite install

If you’re not on one of your sites, ie someone else’s site that you don’t administer in a WordPress Multisite install, my function below to remove nodes won’t work because it checks for current blog id.

I want to disable the dashboard link (and others) in the toolbar for each of the person in the dropdown under “My Sites” no matter who’s site they are viewing.

Is there a way to remove the node site wide? Since the remove_node is based on blog id, I’m having trouble thinking of a way to do this.

add_action( 'admin_bar_menu', 'remove_toolbar_items', 999 );

function remove_toolbar_items( $wp_admin_bar ) {

   $blog_id = get_current_blog_id(); // get blog id

   $wp_admin_bar->remove_node( 'blog-' . $blog_id . '-d' ); // Dashboard
   $wp_admin_bar->remove_node( 'blog-' . $blog_id . '-c' );  // Manage Comments
   $wp_admin_bar->remove_node( 'new-media' );
   $wp_admin_bar->remove_node( 'wp-logo' );
}

1 Answer
1

To get all blogs/subsites a user is registered to, use get_blogs_of_user()

$sites = get_blogs_of_user( get_current_user_id() );

This will fetch all sites that aren’t marked as archived, spam or deleted. This will as well work in a single site environment, returning a an array with a single numerical key that has a stdClass object as value:

$sites = array( 0 => stdClass
    userblog_id -> $blog_id
    blogname    -> get_option('blogname')
    domain      -> ''
    path        -> ''
    site_id     -> 1
    siteurl     -> get_option('siteurl')
    archived    -> 0
    spam        -> 0
    deleted     -> 0
);

If it’s a multisite environment, it will use get_blog_details() to fetch the sites details.


Note that there’s a filter at the end (right before it gets added to the cache) of the get_blog_details() function to adjust the returned details:

$details = apply_filters( 'blog_details', $details );

Note that there’s a filter at the end of the get_blogs_of_user() function that allows you to adjust the returned objects:

return apply_filters( 'get_blogs_of_user', $blogs, $user_id, $all );

You could then adjust your admin bar nodes with something along the following lines:

<?php
/** Plugin Name: WPSE (#165787) Remove Admin Toolbar Comments, Dashboards, Media & Logo */

add_action( 'admin_bar_menu', 'remove_toolbar_items', PHP_INT_MAX -1 );
function remove_toolbar_items( $bar )
{
    $sites = get_blogs_of_user( get_current_user_id() );
    foreach ( $sites as $site )
    {
        $bar->remove_node( "blog-{$site->userblog_id}-c" );
        $bar->remove_node( "blog-{$site->userblog_id}-d" );
    }
    $bar->remove_node( 'new-media' );
    $bar->remove_node( 'wp-logo' );
}

Note that above plugin isn’t tested, so you might need to var_dump( $site ); in the foreach() loop and $bar to see if you are removing the right nodes (or any at all).

Leave a Comment