12% off of LTD using this coupon: TWELVEPERCENTOFF. Promo ends on 2 Dec midnight UTC.
Published on Mar 17, 2022

Button to Copy a Custom Field’s Value on Click to Clipboard Using WordPress REST API

Sridhar Katakam

This members-only tutorial provides the steps to add a button on single Posts/Pages which when clicked, copies the value of a specified custom field for that entry into user's clipboard using the WordPress REST API.

Live Demo

We shall

  • register a custom field say, hydrogen_code using either ACF or Meta Box.
  • load a js file on single posts (and/or on Pages as needed) while passing a data object containing the ID of the entry.
  • access this in the js file and use it to retrieve that post object via WP REST API, then in the button's click event handler add code to copy the custom field's value referenced from the post object.

Note: In this example we are fetching the post on page load. It is also possible to instead do this on the button click. There may be a slight delay in this case and you may want to then show a loading spinner.

Step 1

Install and activate the custom fields plugin of your choice - ACF or Meta Box.

Add a field group having a Textarea-type of field.

Let its name (if using ACF) or ID (if using MB) be say, hydrogen_code.

If using ACF, toggle "Show in REST API" to Yes under Settings.

Set the group to appear on your desired post type, post in this example.

Step 2

Install and activate My Custom Functionality plugin.

Connect to your hosting account using a FTP client and navigate to site's /wp-content/plugins/my-custom-functionality-master.

Create a file named say, single.js having the following code and upload to the plugin's assets/js directory:

This is a premium members-only content.

To view the rest of the content, please sign up for membership ($47/month or $599 one-time).

Already a member? Log in below or here.

tagschevron-leftchevron-rightchainangle-rightangle-upangle-downfolder-omagnifiercrossmenuchevron-downarrow-right