Add Snippet To Project
In WordPress, the TinyMCE HTML editor is a popular tool used by many users to format and customize their website content. However, sometimes you may want to restrict the use of this feature to only a specific user role, such as the admin. In this article, we’ll show you how to disable the TinyMCE HTML editor for everyone except the admin, and also provide an alternative solution for non-admin users to edit their content. Let’s dive in.
function wpturbo_disable_tinymce_html_editor() {
if ( ! current_user_can( 'manage_options' ) ) {
add_filter( 'user_can_richedit', '__return_false', 50 );
}
}
add_action( 'init', 'wpturbo_disable_tinymce_html_editor' );
The code snippet above creates a function named wpturbo_disable_tinymce_html_editor()
. This function is used to disable the HTML editor in the TinyMCE editor for all users except for the administrator.
The code block checks if the current user does not have the manage_options
capability. This capability is usually associated with the administrator role, which grants the user full access to the WordPress dashboard. If the user does not have this capability, the user_can_richedit
filter is applied with a callback function __return_false
.
The user_can_richedit
filter decides whether TinyMCE should be loaded for a user or not. By setting the filter to false, the HTML editor will not appear for any post or page editor for that user. This eliminates the risk of accidental or intentional changes to the website’s HTML by unprivileged users while still allowing the administrator to use the HTML editor.
Lastly, the function is hooked into the WordPress action init
so that it is fired during the initialization of WordPress. This ensures that the function runs before the post editor is loaded, and the HTML editor will be properly disabled for the right users.