1

I'm looking to add an attribute to a shortcode used in a post dynamically. For example, say we start with:

[shortcode-name]

I'd like to add the "attribute=xxx" portion to the shortcode so it is effectively like so:

[shortcode-name attribute=xxx]

For just the first shortcode encountered in a post. Is this possible?

Thanks!

3

Untested (and can't test right now) but you ought to be able to add attributes with a filter... something like:

function test_sc($atts,$content) {
  // echo 'test_sc';
  $atts = shortcode_atts(
      array(
              'foo' => 'no foo',
              'bar' => 'default bar',
      ), 
      $atts, 
      'testsc' 
  );

  // var_dump($atts);

}
add_shortcode('testsc','test_sc');

function test_shortcode_att_add($atts) {
  # this filter should only run once (first use on page)
  remove_filter('shortcode_atts_testsc','test_shortcode_att_add');
  $atts['xxx'] = 'yyy';
  return $atts;
}
add_filter('shortcode_atts_testsc','test_shortcode_att_add');

Of course, I don't know exactly what you attribute you are trying to add, or what kind of supporting code it might depend on.

  • That should work just fine. I did this recently for a plugin and it worked out well. – Pippin Apr 9 '15 at 20:11
  • Fixed a bug (third shortcode_atts parameter didn't match shortcode name) and added a var_dump() to make it a bit more obvious. – William Turrell Apr 10 '15 at 8:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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