Using Advanced Custom Fields to create global calls to action

Cory Pratt

A client recently asked if there was a way to create an easy way to create and manage 'calls to action' that could be put into posts using a shortcode. We decided a good solution would be to use Advanced Custom Fields (ACF) to create and store the CTA's that could later be referenced via a shortcode's attribute.

Setting up ACF

The first step is setting up an Options Page where we can store setup the fields and later create and manage the CTAs. Once the code is in place, you should have a new item in the admin sidebar titled "Theme Settings" and a sub-item titled "Global CTA".

Next it's time to start creating your fields for the CTAs. Create a new Field Group, I named mine "Global CTA", add a Repeater Field named "CTA". Add any fields that are necessary for your CTA. As you are creating your field, you will need to create one that is the key or ID of the cta. This is field is required, I named mined "Unique ID" and is used to reference the CTA fields in a shortcode.

Once the fields are created, set the field group to load on the options page:

Screen Shot 2019 04 09 At 8 56 12 Am

The last bit of code necessary is the creation of the shortcode. We use this code to take the "id" attribute being passed in, look through the cta options for a match and output the fields. The bones of the code will be the same for most all implementations, but what is returned is unique for every situation.

The shortcode is rather simple as it only takes one attribute, id, a use case would be [globalcta id="ebook_purchase_v1"]. Where the code would look for a CTA with a unique id of 'ebook_purchase_v1'.

Breaking down the code a little bit:

  • Line 13: Looks for to see if there are any repeater fields named 'CTA' in the options. You will need to update according to what you named the repeater field.
  • Line 20: This is where the unique id becomes important. It looks through the CTA's for a matching unique id to what was passed in the shortcode. Again, important to modify accordingly.
  • Lines 21: Write whatever code necessary to populate the fields you've setup.

Now, as the shortcodes are populated throughout the site, you can edit the CTA's: swaping images, text, urls, etc. and the changes will happen globally.