I want to protect from copy and paste/right-clicking only the content of this custom field:
$cin = esc_html__(get_post_meta( $post->ID, 'cin_code', true), 'sacconicase');
Up to now I found solutions only for the entire site content, such as this java, to be put in js folder
document.addEventListener( 'contextmenu', function(e) {
e.preventDefault();
}, false);
I tryed doing
if ( ! empty( $cin)) {
$cin = '<div class="not-clickable">'. $cin .'</div>';
}
and than by css the "pointer-events: none" to that class but it’s not working
2
Answers
You can disable right clicking on a specific element by setting the event listener on it, instead of the entire document:
This targets an element with the id "two" and will disable the context menu on it with
e.preventDefault();
Your next step is to prevent users from selecting the text. This way they can’t copy paste it. You can use CSS to achieve this:
Even when someone uses Ctr+A in an attempt to select everything, it’ll still not select the element where you use the CSS code on.
Finally, a working example where you cannot right click the red element and cannot select the text inside it:
Your PHP code looks correct in adding the wrapper around your text. I’m not sure what CSS you had tried adding, but below is the working client-side component. As you can see, the user cannot select the text or open the context menu on it, but is still able to open the context menu on the rest of the page.
Note: If you use
pointer-events: none;
, the JavaScript will not be able to determine the user has right clicked on the specified element and will display the context menu.Breakdown: Rather than selecting the entire document, select only elements with the class
not-clickable
. UsingquerySelectorAll
rather than an ID means you can add thenot-clickable
class to multiple elements to deter users from copying sensitive text in other instances as well.Edit:
Adding the JavaScript to your page.
I’m assuming your using WordPress because you used
get_post_meta
, so here is a breakdown of where to add the JavaScript:In your theme folder, navigate to the js directory (create it if it doesn’t exist)
Create a file called
not-clickable.js
and paste the JS code into itAdd this PHP to your themes
functions.php
file: