skip to Main Content

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 
}
?>

3

Answers


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

    Login or Signup to reply.
  2. 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' );
    
    Login or Signup to reply.
  3.  
    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 }
    
        }
      }
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search