Wordpress shortcodes pass array of values Wordpress shortcodes pass array of values wordpress wordpress

Wordpress shortcodes pass array of values


foreach would be your answer here. It will be the easiest and cleanest in my opinion. Before I give you a code example, lets analyze your code and look at all your flaws and how we will correct them

FLAWS

  • Never ever use extract(). exctract() creates variables on the fly which is problematic. You cannot properly debug extract() (if you even can), so when it fails you really have your work cut out for you, unnecessarily. For these reasons, it was completely removed from core and the codex. See trac ticket 22400. You should have an evil list with query_posts and extract() in the top two positions, that i how bad these two are.

  • You are not sanitizing and validating input data which can lead to hacker injecting jquery into your code in order to hack your site. Never trust any data that comes from user side and URL's, it might be infected.

  • As you already know, taken from your code, shortcodes cannot except array value, the values must be string. In your case, we need to create an array from string values. Again, because you can't trust a user to not use spaces before or after commas, it is wise and recommended to remove all white spaces, if any, in order for your explode function to correctly create your array

  • With this new approach, you need to make sure that your values in your strings are the in the correct order and that the strings is the correct lenght. If not, you will get unexpected output

Lets tackle the first shortcode: (PLEASE NOTE: All the code below is untested. It might be buggy or have syntax errors)

internal-menu

//menufunction internal_menu( $atts ) {    $attributes = shortcode_atts(        array(           'href' => '',         ),         $atts    );    $output = '',    // Check if href has a value before we continue to eliminate bugs    if ( !$attribute['href'] )        return $output;    // Create our array of values    // First, sanitize the data and remove white spaces    $no_whitespaces = preg_replace( '/\s*,\s*/', ',', filter_var( $attributes['href'], FILTER_SANITIZE_STRING ) );     $href_array = explode( ',', $no_whitespaces );    $output .= '<div id="internalPageMenu">';        $output .= '<ul>';            foreach ( $href_array as $k => $v ) {                 // From your code, link 1 is different, so I kept it as is                if ( $k == 0 ) {                    $output .= '<li><a href="#' . $v . '"><i class="fa fa-bars"></i>link 1</a></li>';                } else {                     $output .= '<li><a href="#' . $v . '">link ' . ($k + 1 ) . '</a></li>';                }            }        $output .= '</ul>';    $output .= '</div>';    return $output;}add_shortcode( 'internal-menu', 'internal_menu' );

You can then use the shortcode as follow

[internal-menu href='jl1, jl2, jl3, jl4']

internal-menu-target

//menu targetfunction internal_menu_target($atts) {    $attributes = shortcode_atts(        array(           'id' => '',           'text' => '',         ),         $atts    );    $output = '',    // Check if href has a value before we continue to eliminate bugs    if ( !$attribute['id'] || !$attribute['text'] )        return $output;    // Create our array of values    // First, sanitize the data and remove white spaces    $no_whitespaces_ids = preg_replace( '/\s*,\s*/', ',', filter_var( $attributes['id'], FILTER_SANITIZE_STRING ) );     $ids_array = explode( ',', $no_whitespaces_ids );    $no_whitespaces_text = preg_replace( '/\s*,\s*/', ',', filter_var( $attributes['text'], FILTER_SANITIZE_STRING ) );     $text_array = explode( ',', $no_whitespaces_text );    // We need to make sure that our two arrays are exactly the same lenght before we continue    if ( count( $ids_array ) != count( $text_array ) )        return $output;    // We now need to combine the two arrays, ids will be keys and text will be value in our new arrays    $combined_array = array_combine( $ids_array, $text_array );    foreach ( $combined_array as $k => $v )        $output .= '<h3 id="' . $k . '">' . $v . '</h3>';    return $output;}add_shortcode('internal-menu-target', 'internal_menu_target');

You can use this shortcode as follow:

[internal-menu-target id='1,2,3,4' text='text 1, text 2, text 3, text 4']


Problems:

Wordpress shortcodes have some painful restrictions in the format of the data which can be passed...

space-delimited variables:

[shortcode a="1 2"]

result: $atts=['a'='"1', 0='2"']

']' closes the shortcode:

[shortcode b=[yay]]

result: $atts=['b'='[yay']

Solution:

You can get around this by using urlencode():

[shortcode atts=a=1+2&b=%5Byay%5D]

parse it like so:

parse_string($atts['atts'],$atts);

result: $atts=['a'=>'1 2', b=>'[yay]']

That will give you the array passing you want.

Now as for building your menu(s):

function internal_menu($atts) {  // allow passing + and ] in the text of the links:  parse_string($atts["links"],$links);  // the defaults, verbatim from the question:  if (!count($links)) $links=[    'href1' => '#jl1',    'href2' => '#jl2',    'href3' => '#jl3',    'href4' => '#jl4',  ];  foreach ($links as $text=>$href) $ul=."<li><a href=\"$href\">$text</a></li>";  return '<div id="internalPageMenu"><ul>'.$ul.'</ul></div>';}add_shortcode('internal-menu', 'internal_menu');//menu targetfunction internal_menu_target($atts) {  // allow passing + and ] in the text:  if (@$atts[text]) $atts['text']) = urldecode($atts['text']);  // the defaults, verbatim from the question:  $atts=array($atts)+['text'=>'','id'=>'jl1'];  return '<h3 id="' . $link['id'] . '">' . $link['text'] . '</h3>';}add_shortcode('internal-menu-target', 'internal_menu_target');

and then feed it like so:

[internal-menu links=First+Link=#jl1&Second+Link=#jl2&Google=https://google.com][internal-menu-target text=Section+1 id=jl1]

etc.

BTW extract() is perfectly fine if you use it responsibly:

/* concatenates 3 words of wisdom into a polite policy direction * * @param $attr: hash of function args *          foo = the first word (Kindly) *          bar = the second word (ignore) *          baz = the third word (totalitarians) */function excellent_policy($attr){  $defaults=['foo'=>'Kindly', 'bar'=>'ignore', 'baz'=>'totalitarians'];  extract((array)array_intersect_key($attr,$defaults)+$defaults);  echo "$foo $bar $baz!";}

This imports $foo, $bar, and $baz from $attr into local scope in a readable and predictable manner, provides defaults for those variables if they were not passed, and prevents the creation of any unexpected variables.

There's good ways and bad ways to use language features. Forbidding everyone from using a language feature because someone might use it poorly is like forbidding everyone from breathing because someone might try to inhale Jello.


Simple way I use:

[my param="key1=value1&key2=value2"]

in shortcode callback, just do:

parse_str( str_replace("&", "&", $attrs['param']), $array);// var_dump( $array );