I am writing a function to add a link to the Media Library in the admin menu on front end:

function add_media_link_to_admin_menu( $wp_admin_bar ) {

    // add Media Library to admin menu
        $wp_admin_bar->add_menu( array(
            'parent' => 'appearance',
            'id'     => 'media-library',
            'title'  => 'Media Library',
            'href'   => '/wp-admin/upload.php',
        ) );
        
}

// restrict to only users who can upload media
if ( !current_user_can( 'upload_files' ) ) {

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

}

Without the "if ( !current_user_can( 'upload_files' ) ) {" the function works fine. But with the if statement, I get a critical error.

Am I missing something? I just want to check if user can upload files. If not, they don't need the Media Library link.

Thanks, Chris

有帮助吗?

解决方案

The problem is that wp_get_current_user (which current_user_can relies upon) is pluggable, which means it isn't loaded until after plugins are loaded (to give plugins a chance to override it). That means it's not available to call from the top level of a plugin file.

Instead, I'd make the role check inside the hook e.g.

function add_media_link_to_admin_menu( $wp_admin_bar ) {
    if ( current_user_can( 'upload_files' ) ) {
        // add Media Library to admin menu
        $wp_admin_bar->add_menu(array(
            'parent' => 'appearance',
            'id' => 'media-library',
            'title' => 'Media Library',
            'href' => '/wp-admin/upload.php',
        ));
    }
}
add_action( 'admin_bar_menu', 'add_media_link_to_admin_menu', 999 );

(However themes are loaded after pluggable functions, so your original code would work fine in a theme.)

许可以下: CC-BY-SA归因
scroll top