Using Custom Fields in WordPress Shortcodes
As a WordPress addict, I probably spend a chunk of my day thinking about cool new tricks and hacks to test out. Today, I came up with a potential scenario that prompted me to attempt using custom fields in shortcodes. Here’s that scenario:
A user wants to insert some WooCommerce products into a specific part of their theme (Genesis in this example) that is not part of the normal content. Say, for example, the user wants to add a few featured products before the actual content area on a specific page (the home page in this example). Normally, the person could just paste the [products ids=”…”] WooCommerce shortcode into the editor but, since they want the products to outside of that content area, this shortcode will need to be placed in a template file or functions file if your theme includes the appropriate hooks. Now, let’s say that the user is totally, 100% code illiterate and is not comfortable making the slightest PHP edits. Okay, no problem! Let’s create a custom field that the user can enter a few product IDs into and then dynamically insert these IDs into the shortcode. By doing this, the user can simply type in a few product IDs separated by a comma and the code will automatically insert these ID’s into the shortcode.
The first thing we need to do is create a custom field. You can use the default WordPress UI for creating this field or you can use something like Advanced Custom Fields. In this example, I’m going to be using Advanced Custom Fields to create the custom field so the syntax will be specific for the ACF plugin.
Let’s run through the steps now (although this scenario is specific to WooCommerce shortcodes, the same concept can be applied to any shortcode).
- First, create a custom field for your home page called featured_products_ids.
- Next, add an action for the code to execute before your page’s content (‘genesis_before_content’ in our example using the Gensis Framework). Our action’s function will be a conditional that ensures the products are displayed only on the home page. If you are not using Genesis or some other framework that provides a hook for where you want to output the content, you’ll need to create a new template or modify an existing one.
- Finally, create a variable inside the function to store the custom field’s data. This variable will be concatenated with the rest of the
do_shortcode()function. This is very important because I found trying to concatenate the get_post_meta() function inside do_shortcode() will not work.
There you have it. Again, this concept can be applied to any shortcode.