skip to Main Content

I wanted to disable right click on my wordpress site. I have written a small snippet and inserted into body which disables right click, CTRL events and keyups.

<body oncontextmenu="return false" onselectstart="return false" onkeydown="if ((arguments[0] || window.event).ctrlKey) return false"></body>

but it is annoying when I want to copy something on site. is there a way I can modify the current snippet like only logged in users would be able to access the disabled events?

Cheers.

4

Answers


  1. Chosen as BEST ANSWER

    First I have created a JS page in the directory named: "preventcopy.js" and added restricted the events using below JS

    document.oncontextmenu = function() {
      return false
    };
    document.onselectstart = function() {
      if (event.srcElement.type != "text" && event.srcElement.type != "textarea" && event.srcElement.type != "password") return false;
        else return true;
      };
      if (window.sidebar) {
        document.onmousedown = function(e) {
          var obj = e.target;
          if (obj.tagName.toUpperCase() == "INPUT" || obj.tagName.toUpperCase() == "TEXTAREA" || obj.tagName.toUpperCase() == "PASSWORD") return true;
         else return false;
      }
    };
    if (parent.frames.length > 0) top.location.replace(document.location);
    

    and then in function.php I enabled access for logged in users as below.

    function copyrightpro_scripts() {
        wp_enqueue_script( 'copyrightpro', get_template_directory_uri() . '/copyprevent.js', array(), false );
    }
    if ( !is_user_logged_in() ) {
        add_action( 'wp_enqueue_scripts', 'copyrightpro_scripts' );
    }
    

    That's how it is been accomplished. But I would highly suggest enabling these features for users considering the user experience.


  2. Why not using existing wordpress plugin?

    for example using this

    This plugin is used to disable right click on website to prevent cut, copy, paste, save image, view source, inspect element etc.

    But when Administrator or Site Editor is logged in, he can access everything without any of the above restrictions.

    Login or Signup to reply.
  3. You could simply put a conditional inside the body tag. You would want this in your theme’s header.php file. You also want the wordpress function body_class to include all of the other classes that should appear in the body tag.

    <body <?php if ( !is_user_logged_in() ) {
        echo 'oncontextmenu="return false" onselectstart="return false" onkeydown="if ((arguments[0] || window.event).ctrlKey) return false"';
    } ?> <?php body_class(); ?>>
    
    Login or Signup to reply.
  4. Just disable context menu not select or other events.

    <body <?php if(!is_user_logged_in()) { echo 'oncontextmenu="return false"'; }?>></body>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search