The WPFolks app is out on iPhone and Android. Free, no ads. Download on the App Store Get it on Google Play
Skip to main content
Login Join
Snippet · PHP

Copy URL Button

Shared by Rashed Hossain · August 17, 2026

28 views
Back to Snippets

2 approaches to this. Compare them and pick what fits your setup.

Faster method by Rashed Hossain

Here's a lightweight WordPress code snippet that adds a Copy URL button to every single post and page. It uses the modern Clipboard API, has no dependencies, and works by adding the button after the post content.

Features

  • ✅ No plugin required

  • ✅ Works on Posts and Pages

  • ✅ Uses the Clipboard API

  • ✅ Shows "Copied!" feedback

  • ✅ Lightweight (CSS + JS included)

Add to functions.php

/**
 * Add Copy URL button below post content.
 */
function txwp_copy_url_button( $content ) {

	if ( ! is_singular() || ! in_the_loop() || ! is_main_query() ) {
		return $content;
	}

	$url = esc_url( get_permalink() );

	$button = '
	<div class="txwp-copy-url-wrapper">
		<button class="txwp-copy-url" data-url="' . $url . '">
			🔗 Copy Link
		</button>
	</div>';

	return $content . $button;
}
add_filter( 'the_content', 'txwp_copy_url_button' );

/**
 * Add styles and script.
 */
function txwp_copy_url_assets() {
	if ( ! is_singular() ) {
		return;
	}
	?>
	<style>
	.txwp-copy-url-wrapper{
		margin-top:24px;
	}

	.txwp-copy-url{
		background:#2563eb;
		color:#fff;
		border:none;
		padding:12px 18px;
		border-radius:10px;
		font-size:15px;
		font-weight:600;
		cursor:pointer;
		transition:.2s;
	}

	.txwp-copy-url:hover{
		background:#1d4ed8;
		transform:translateY(-1px);
	}
	</style>

	<script>
	document.addEventListener('DOMContentLoaded', function () {
		document.querySelectorAll('.txwp-copy-url').forEach(function(button){

			button.addEventListener('click', async function(){

				const url = this.dataset.url;

				try{
					await navigator.clipboard.writeText(url);

					const original = this.innerHTML;
					this.innerHTML = '✅ Copied!';
					this.disabled = true;

					setTimeout(()=>{
						this.innerHTML = original;
						this.disabled = false;
					},1500);

				}catch(e){
					alert('Failed to copy the link.');
				}
			});
		});
	});
	</script>
	<?php
}
add_action( 'wp_footer', 'txwp_copy_url_assets' );
Know a different way to do this? Add your approach as a variation so folks can compare them side by side.
Submit a variation

0 comments