Hack: Add a Copy Link Button With a Shortcode

Sometimes it can be handy to have a little button on a post where a user can click and the URL for this post is placed in the clipboard. Hey, you want to make it as easy as possible for someone to share your posts, right?

Here is a bit of code that adds a shortcode to your post with an input field that includes the link, plus a button next to it that allows the user to copy it with a click or tap.

add_shortcode('copy_shortlink','wpshortcode_copy_shortlink');
function wpshortcode_copy_shortlink() {
	//$link = wp_get_shortlink();
	$link = get_permalink();
	$out = '<input type="text" value="'.$link.'" id="thisURL"><button onclick="clickURL()">COPY</button>';
	$out .= '<script>function clickURL() { document.getElementById("thisURL").select();document.execCommand("copy");alert("Copied '.$link.'"); }</script>';
	return $out;
}

Note that there are two $link = lines. The first will use the short link, usually a ?p=100 kind of thing. These are nice and short, but ugly. The second uses the regular URL for the post. So comment out the one you don’t want to use. Then just put this shortcode in your post anywhere you want.

[copy_shortlink]

You can add styling to the input and/or button using a style tag right in there, or add a class and put some styling in your CSS. You can also leave out the button altogether and put the onclick function right on the input field. Some users would then try to select the text and be pleasantly surprised when they get the copy without much effort.

The heavy lifting here is done by JavaScript, with the text being selected and then copied. Then an alert to give the user some feedback.

Leave a Reply

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