wordpressuser-roleswordpress-capabilities

Disable editing page titles for users except admin


How to disable page title editing for users except admin ? they should be able to see page title, but should not be able to edit page title in backend.

function disableAdminTitle () {
    $user = wp_get_current_user();
    if(!in_array( 'administrator', (array) $user->roles )){
        wp_enqueue_script('admin_title_disable');
    }
}
add_action('admin_enqueue_scripts', 'disableAdminTitle');

function admin_footer_hook(){
        ?>
    <script type="text/javascript">
        jQuery(document).ready(function ($) {
  $('#title').attr('disabled','disabled');
});
    </script>
<?php
}
add_action( 'admin_footer-post.php', 'admin_footer_hook' );


Solution

  • You can try this

    wp_register_script('admin_title_disable', '/path/to/admin_title_disable.js');
    function disableAdminTitle () {
        $user = wp_get_current_user();
        if(!in_array( 'administrator', (array) $user->roles )){
            wp_enqueue_script('admin_title_disable');
        }
    }
    add_action('admin_enqueue_scripts', 'disableAdminTitle');
    

    Js Code

    jQuery(document).ready(function ($) {
      $('#title').attr('disabled','disabled');
    });