0

I'm looking to include a shortcode that builds a table of items and groups of items. For this I wish to be able to include an attribute multiple times or chain them together in some way. An example is I would like to do something like this:

[testcode item="item1" group="group1" item="item2" item="item3" group="group2"]

alternatively something like this could work:

[testcode item="item1"&group="group1"&item="item2"&item="item3"&group="group2"]

The order the parameters appear must be maintained and multiple entries must be allowed. Any suggestions on how to accomplish this without writing completely custom shortcode handler routines?

An array does not seem to maintain the order between items and groups and associative arrays do not seem to be allowed in shortcodes. What I'm looking for is identifying and maintaining item1,group1,item2,item3,group2 order when I process it.

  • 1
    you can simply pass comma separated values inside ITEM aprameter and then use explode to convert in array. Then you can loop through each value usign foreach – Piyush Rawat Nov 6 '17 at 5:52
  • 3
    Possible duplicate of How can i put an array as variable in shortcode_atts? – Jack Johansson Nov 6 '17 at 6:37
  • @Piyush Rawat Using commas does not retain the order properly. For example, if I put item="item1,item2,item3" group="group1,group2", how do I know where in between each item each group was? Retaining the order is important. – Trev Peterson Nov 6 '17 at 15:56
  • @Jack Johansson I don't think it's a duplicate of that question since I believe I can't pass an associative array. I know I can create a custom string that can format it as I want with & separating the value (or json : or other special chars to explode on). I was just hoping there was a more standardized method that could take more advantage of the wordpress shortcode processsing functions. Seems like it's not the case. – Trev Peterson Nov 6 '17 at 16:18
1

Shortcodes are intended to be used by humans, to be some kind of macro that even the most techno-phobic author can use. If you need to have arrays of attributes, or any other complex structure for which the author has to attend CS 101 in order to understand its use, your shortcode is just a fail.

If you need a shortcode with complex data, the more sane way to do it is by separating the placement and the actual data input. Create a meta box section in which users can have a nice UI in inputting the data, and use [myshortcode] in the text just as an indication where that data should be displayed.

  • Agreed. Nice explanation – Piyush Rawat Nov 7 '17 at 7:10
  • Thanks for the comment. I ended up reworking the system to make things easier to arrange. Your comment helped me realize that. Much appreciated. – Trev Peterson Nov 8 '17 at 18:57

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.