How to Copy WordPress Post URL to Clipboard

This tutorial is about how to copy post URL to the clipboard with JavaScript. Let’s do start

Step 1: Add HTML

<a href="#" onclick="copyToClipboard(this)" data-formatted="<?php echo get_the_permalink();?>">
    Copy URL
</a>

Step 2: Add JavaScript

<script>
    function copyToClipboard(text) {
        var inputc = document.body.appendChild(document.createElement("input"));
        var postURL = text.getAttribute("data-formatted"); // Get post URL
        inputc.value = postURL;
        inputc.focus();
        inputc.select();
        document.execCommand('copy');
        inputc.parentNode.removeChild(inputc);
        alert("URL copied into your clipboard.");
    }
</script>

Hope this tutorial is helpful for you.

Note: Please make sure you putted the code inside WP while ( have_posts() ) {} loop

Thanks!


Posted

in

,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *