Only admin should run wordpress plugin shortcode

I have created a simple plugin that locks down content for users not logged in and it is working fine. However any user on a multi-author site could use the same short code in his post to lock down content too. I do not want this to happen.

How may I restrict this functionality to administrators only? This current code thows up a fatal error:Fatal error: Call to undefined function wp_get_current_user()

public function check_user_role() {
  if(current_user_can( 'activate_plugins' )) {
        return true;
    }
}

I then intended to use this method in my class constructor to determine if the add_shortcode() function should run. Any clues how I should go about implementing this shall be appreciated.

Topic plugin-development Wordpress

Category Web


To restrict the use of the shortcode on posts created by administrators only, I need to check if the post author of the post viewed is an administrator as shown in code if ( user_can( $post->post_author, 'activate_plugins' ) ). IF not, the content is returned without executing the do_shortcode($content) function.

The current_user_can() function is not appropriate as it checks the current user and not the post author.

public function check_login($atts, $content = null)
{         
    if (is_user_logged_in() && !is_null($content) && !is_feed())
    {             
        return do_shortcode($content);         
    }
    else
    {
        global $post;           
        if ($post instanceof \WP_Post) {
            if ( user_can( $post->post_author, 'activate_plugins' ) ) {
                return '<p>You must be logged in to view this post..</p>';   
            }
            return $content; 
        }           
    }
}

I hope this helps someone else.


Fatal error: Call to undefined function wp_get_current_user()

This can be fixed by declaring check_user_role only when WP is ready, hooking into wp (to use WordPress functions and methods) or performing other workaround.

Simply check if manage_options capability is there for the user too ( or verify if administrator is in the roles list in_array( "administrator", $current_user->roles ) ):

add_action("wp", function() { 
    function check_user_role() {
        return current_user_can( "manage_options" ) && current_user_can( 'activate_plugins' );
    }
});

Hope that helps.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.