Here’s a post that I wrote as a “Note to Self.” Currently, I’m working on a project that includes a portfolio section with custom fields. Among these fields are those for smaller details (i.e. client, year, location, etc.), which are to be displayed in the sidebar. I could just use HTML and PHP to output and format the data directly but I wanted to give the client a way to change how this data is displayed whenever they want. Therefore, I thought it would be best to create a shortcode that can be used to show the various fields so, down the road, the client can change how the data is shown in the sidebar and add their own markup and styling.
Before getting started, you will need to enable the use of shortcodes in a text widget because this is not something WordPress supports out of the box (I don’t know why). This can be done by pasting the following snippet in your functions.php or, preferably, your own functions plugin.
//* Use shortcodes in text widgets. add_filter( 'widget_text', 'do_shortcode' );
Creating the Shortcode
Next, we have the code that actually creates the shortcode and attribute.
This code creates the [project_info field=””] shortcode. The parameters that can be passed for “field” include client, year, location, and dimensions. These values are pulled from a project’s custom fields. Since the values are populated dynamically, you can now include something like this in a text widget:
Client: [project_info field="client"]
Location: [project_info field="location"]
Year: [project_info field="year"]
Dimensions: [project_info field="dimensions"]
Wrapping Up
This is a quick rundown of how to pull custom fields using a shortcode. Remember to adjust it to your requirements.
Amanda Rush says
Excellent post. If you don’t mind, I’d like to offer some feedback. The only thing I would change about what you present in this post is that this kind of code should be added to a custom plugin and not to the theme’s functions.php file, because when the user switches themes, the functionality will go away but the shortcodes will remain, displaying as shortcodes in the leftover text widgets. Other than that, this is an excellent tutorial.
Ren says
Hey, Amanda. Yes, you’re totally right…good call. In posts like these, I normally link to my article on adding functions to a plugin rather than a theme but I spaced it for this one. I’ll update the post.
Thanks for commenting!