menu

Questions & Answers

Hide a div to user role in one page

I would like to hide a particular div from a specific user role on a page of my site, I tried to insert the following code in the function.php file of my theme, but unfortunately it doesn't work, do you have any suggestions?

<?php
$user = wp_get_current_user();
if ( in_array( 'shop_manager', $user->roles ) ) {
?>
    <script>
jQuery(document).ready(function( $ ){
    jQuery( "#hide" ).empty();
    
});     

    </script>
<?php 
}
?>
Comments:
2023-01-07 20:29:32
Why do you need JS for this? Why not completely remove the markup instead? Also, what exactly is not working with the given code?
Answers(3) :

functions.php is for adding php functions to your site. If you wanted to print out HTML/JS in your theme, you would need to add this to your theme file (index.php or footer.php)

Place this code in your theme file and it should work.

Use the footer hook to inject your css/js code:

function your_function() {
    $user = wp_get_current_user();
    if ( in_array( 'shop_manager', $user->roles ) ) {
        ?>
        <script>
        jQuery(document).ready(function( $ ){
            jQuery( "#hide" ).empty();
        });
        </script>
        <?php 
    }
}
add_action( 'wp_footer', 'your_function' );

 
add_action( 'wp_head', 'callback_hide_div_onpage' ); // wordpress header action hook 
function callback_hide_div_onpage() {
  if( is_user_logged_in() ) {
    $user = wp_get_current_user();
    $roles = $user->roles;
    if($roles[0] == 'student_role'){  // role name -> Student Role
    
      // When the Page with a post_name (slug) of "about-me" is being displayed.
      
      is_page( 'about-us' ){  // add specific page to hide a div using style 
      
      ?>
     
        <style>
          /* hide div using styling css option or you can used script for this as per requirement */
          .target_div{
            display:none !important;  
          }
        </style>
      <?php }

    }
  }
}