Retrieve multiple values passed to a single attribute in a shortcode

All we need is an easy explanation of the problem, so here it is.

How can I retrieve the values ​​passed to the shortcode using only one parameter?

Example:

[related type="2,3,4,5,6"]

Is it possible to do that?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

The solution below will parse the comma separated values passed to the shortcode’s type parameter. We’ll also strip out any whitespace surrounding the values which is a usability improvement (see example 2 after the code below).

add_shortcode( 'related', 'wpse_related' );
function wpse_related( $atts, $content = '' ) {
    // User provided values are stored in $atts.
    // Default values are passed to shortcode_atts() below.
    // Merged values are stored in the $a array.
    $a = shortcode_atts( [
                'type'   => false,
    ], $atts );

    $output = '';

    if ( $a['type'] ) {
        // Parse type into an array. Whitespace will be stripped.
        $a['type'] = array_map( 'trim', str_getcsv( $a['type'], ',' ) );
    }

    // Debugging: Display the type parameter as a formatted array.
    $output .= '<pre>' . print_r( $a['type'], true  ) . '</pre>';

    return $output;
}

Example 1:

[related type="2,3,4,5,6"]

Output:

Array
(
    [0] => 2
    [1] => 3
    [2] => 4
    [3] => 5
    [4] => 6
)

Example 2:

[related type="8, 6, 7,5,30, 9"]

Output:

Array
(
    [0] => 8
    [1] => 6
    [2] => 7
    [3] => 5
    [4] => 30
    [5] => 9
)

Method 2

You can pass a JSON object in a short code:

[related values='{"a":"foo","b":"bar"}']

Then you can retrieve passed attributes using json_decode

public static function myshortcode( $atts, $content = null ) {
    extract( shortcode_atts( array(
        "values" = "",
    ), $atts ) );

    $values = json_decode( $values, true );

    // Your Shortcode Functionality here

}

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply