I have noticed that when Google populates the search results for this question there are actually two different questions being asked by a similar search.
The first asks:
How do I create a shortcode that outputs the value of an Advanced Custom Fields (ACF) plugin field.
The second asks:
How can I dynamically populate a short code using the Advanced Custom Fields plugin.
I was trying to find the answer to the first question, but I will try to show both answers here, so that you do not have to search again.
How do I create a shortcode that outputs the value of an Advanced Custom Fields plugin field.
- To do this you must first install and activate the ACF plugin on your WordPress website. You can download the free version here.
- Create a field group with the information you want to use. You can learn more about how to do this on the ACF website.
- Once you have your field set up you can start creating your shortcode. You are going to do this in the functions.php file of your child theme.
- First create a function. Here is an example<
function my_shortcode() { $myfield = get_field('my_field',false,false); return $myfield ; }
The trick here is to first create a variable using the get_field ACF function and then return that value as the output for the function./li>
- Once that is done you need to register your function as a shortcode.
add_shortcode( 'myshortcode', 'my_shortcode' );
- Putting it all together you get
function my_shortcode() { $myfield = get_field('my_field',false,false); return $myfield ; } add_shortcode( 'myshortcode', 'my_shortcode' );
- First create a function. Here is an example<
It is important to note that you only need to worry about this if you are using more advanced field than just a text field. If you are only using a text field you can use the inbuilt ACF shortcodes.
e.g.
[acf field="field_name" post_id="123"]
You can learn more about that here.
How can I dynamically populate a short code using the Advanced Custom Fields plugin.
Since I didn’t have to actually code this, I am taking it from an example I found on StackOverflow. You can read it here.
Say you have an ACF field ‘contact_form’ which is the ID of a contact form 7 form. You want to populate this ID dynamically using ACF.
Your normal short code that you would use in a template is
echo do_shortcode( '[contactform id="1457"]' );
To get this to work is as simple as
echo do_shortcode( '[contactform id="'.get_field('contact_form').'"]' );
The trick here is to use the ACF get_field() function instead of the ACF the_field() function.
Please note that the contact form 7 short code has been changed so that it is not called here, and you can see how we use it. Otherwise we get a 404 contact form shortcake showing.
I hope this helps.
If you have any questions please leave a comment below.