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?
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It only takes a minute to sign up.
Sign up to join this communityThe 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
)
array_map ( 'trim', str_getcsv( $a['type'], "," ) );
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
}
extract()
is no longer recommended in this context, makes it e.g. harder to debug.