How to accept an array in a shortcode

WordPress code

I was recently working on a client site when I needed to create a shortcode that would accept several attributes. Some of these attributes needed to be arrays, because the function that they were being passed to required an array for some of the variables.

So I started out by creating the shortcode and setting up the attributes that I wanted to collect data for. My shortcode looked like this:

This basically sets up the shortcode and sets the default options (for when an attribute is not declared in the shortcode).

Being that the function I wanted to pass the information to already existed in another plugin, I just needed to return the data to the function. Since the titles and labels attributes accept arrays, I needed a way of translating the shortcode input into an array so that it could be passed to the function.

The way I did this was to separate the values in the attribute by a comma and a space. So my shortcode might look like this:

You can see that there are multiple values for the titles and labels, as mentioned above.

When passing that data to the function that will be using it, we can use the explode() function to create the array. Here is how it looked in the end:

You’ll notice in the chainselect_categories function that I am using the explode function to create the array, and dictating that the values will be separated by a space and a comma (‘, ‘).

Now the function receives the data as an array and can function as intended.

5 thoughts on “How to accept an array in a shortcode”

  1. Mike iLL says:

    Sweet! Thanks for the tip, man. Using in my plugin MZ Mindbody API to accept a list of items to HIDE in a page.

  2. david says:

    How i can add extra attribute like style into shortcode_attr using filters

    1. You can’t. You’d have to remove the first shortcode (remove_shortcode()) and then add it back in with the new attributes

  3. what happen when I’m not provide the titles parameter
    e.g. [ajax_chain_select] it will explode array because default value of titles is array

  4. You’re right. Maybe the better thing to do would be to change the default to a string: 'titles' => 'Please select…'

Leave a Reply