0

I need to pass complex json with nested array of object as shortcode parameter.

For example I need to pass something like this:

{
   "a":"va",
   "b":{
      "b1":"vb1",
      "b2":[
         {
            "kb2":"vb2"
         }
      ]
   }
}

So I tried to set the shortcode in this way:

[my_shortcode parameters='{"a": "va", "b": {"b1": "vb1", "b2": [{"kb2": "vb2"}]}}']

The problem seems to be related to array (square brackets) indeed this other example works:

[my_shortcode parameters='{"a": "va", "b": {"b1": "vb1"}}']

Here is how parameters are handled in shorcode:

function myshortcodehandler($atts){        
    $arrparameters = json_decode($atts["parameters"], true);
    ob_start(); 
    ?>        
    <pre><?php echo json_encode($arrparameters); ?></pre>        
    <?php
    return ob_get_clean();
}

If json includes some nested array the output show only some brackets. So, what is the right way to pass complex json as shortcode parameter?

I've already red this documentation: https://codex.wordpress.org/Shortcode_API#Square_Brackets

Thanks in advance.

3
  • 1
    This seems like you're really stretching what shortcodes are supposed to be used for. Why do you need such a complex parameter? Are users going to be typing these values in? Jul 14 '21 at 10:02
  • the solution is really quite dependent on how this is being implemented - where does the JSON come from?
    – Paul G.
    Jul 14 '21 at 10:21
  • The shortcode needs complex configuration and will be generated automatically. Users will just copy and paste the shortcode where they want.
    – assistbss
    Jul 14 '21 at 10:40
0

Maybe there is a better solution, but serialize seems to do the job.

Instead of json I could pass json_decoded and then serialized parameters.

For example

$jsonval = json_decode('{"foo": "bar"}');
$serialized = serialize($jsonval);

Shortcode will be something like:

[myshortcode parameters='O:8:"stdClass":1:{s:8:"foo";s:3:"bar";}']

At this point I can handle parameters unserializing them:

function myshortcodehandler($atts){        
    $arrparameters = (array) unserialize($atts["parameters"]);
    ...

Seems to work also with array in json.

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.