4

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?

2 Answers 2

6

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
)
2
  • 3
    We could simplify it with e.g. array_map ( 'trim', str_getcsv( $a['type'], "," ) );
    – birgire
    Jun 9, 2017 at 19:25
  • 2
    Clever! Thanks for that, @birgire. I've updated my answer. Jun 9, 2017 at 19:34
1

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

}
1
  • 2
    Probably not as userfriendly as csv input. Note that extract() is no longer recommended in this context, makes it e.g. harder to debug.
    – birgire
    Jun 9, 2017 at 19:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.