0

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

1
  • 2
    In future, if you're asking about a critical error can you include the details of the error in the question too please? You'll find them in the email the site sends or in your server error log or PHP error log, or in wp-content/debug.log if that's enabled.
    – Rup
    Commented Mar 22, 2021 at 0:38

1 Answer 1

0

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.)

1
  • Yup. That did the trick. Thanks for the advice on posting the critical error details. Will do next time, for sure. And thanks for the tip on when the function is loaded. I really appreciate it! Commented Mar 23, 2021 at 2:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.