Retrieve multiple values passed to a single attribute in a shortcode

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
)

Leave a Comment

tech