0

Right now I'm creating shortcodes like this:

function short_code($atts) {
  $a = shortcode_atts( array(
    'name' => ''
  ), $atts );

return '<div class="content">
  <div class="container">
    <p>' . esc_attr($a['name']) . '</p>
  </div>
</div>';
}
add_shortcode( 'short-code', 'short_code' );

// Usage: [short-code name="John"]

How to do it so I can have incremental shortcodes? In other words, to modify the shortcode so I can do this? [short-code name="John" name="Jack" name="Mary"] and produce something like this?

<div class="content">
  <div class="container">
    <p>John</p>
    <p>Jack</p>
    <p>Mary</p>
  </div>
</div>

I searched on Google but I couldn't find anything.

1 Answer 1

2

What you want is to use shortcode attributes. I Googled "wordpress shortcode attributes" and found the sample code below in the WP Codex

// [bartag foo="foo-value"]
function bartag_func( $atts ) {
    $a = shortcode_atts( array(
        'foo' => 'something',
        'bar' => 'something else',
    ), $atts );

    return "foo = {$a['foo']}";
}
add_shortcode( 'bartag', 'bartag_func' );

You would want to pass an array for the example you show in your question

[short-code names="John", "Jack", "Mary"]

You can get the list of names by following the sample code and accessing the names array:

foreach($a['names'] as $name){
    echo "<p>$name</p>";
}

Edit: Just to be clear you would get the array from args as such:

$a = shortcode_atts( array(
    'names' => 'names'
), $atts );

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.