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"]
This is a quick rundown of how to pull custom fields using a shortcode. Remember to adjust it to your requirements.