Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress shortcodes pass array of values

I am creating some WordPress short codes aimed at providing internal navigation on a page (one page with a lot of content sections and it own menu).

This is what I have:

//menu
function internal_menu($atts) {
  extract(shortcode_atts(array(
   'href1' => '#jl1',
   'href2' => '#jl2',
   'href3' => '#jl3',
   'href4' => '#jl4',
  ), $atts));
  return '<div id="internalPageMenu">
    <ul>
        <li><a href="' . $href1 . '"><i class="fa fa-bars"></i>link 1</a></li>
        <li><a href="' . $href2 . '">link 2</a></li>
        <li><a href="' . $href3 . '">link 3</a></li>
        <li><a href="' . $href4 . '">link 4</a></li>
    </ul>
    </div>';
}
add_shortcode('internal-menu', 'internal_menu');

//menu target
function internal_menu_target($atts) {
  extract(shortcode_atts(array(
   'id' => 'jl1',
   'text' => '',
   ), $atts));
   return '<h3 id="' . $id . '">' . $text . '</h3>';
}
add_shortcode('internal-menu-target', 'internal_menu_target');

And using this in my Wordpress admin panel:

[internal-menu]
[internal-menu-target id="jl1"]
Some content
[internal-menu-target id="jl2"]
...etc...

How do I make the menu dynamic (not restricted to the number of items it can have)? For example the short code would be:

[internal-menu targets="jl1, jl2, jl3, jl4, jl5, ...etc..."]
like image 326
mcneela86 Avatar asked Jul 09 '15 02:07

mcneela86


People also ask

How to create shortcodes with optional parameters in WordPress?

In case if you want to create shortcodes with optional parameters then you can also do it. We will use wordpress function shortcode_atts (). This is a wordpress function used to define attributes and their default values for shortcode. It takes 2 parameters and both are required. $defalt_array – an array with attributes and their values.

How to define attributes and their default values for shortcode in WordPress?

We will use wordpress function shortcode_atts (). This is a wordpress function used to define attributes and their default values for shortcode. It takes 2 parameters and both are required. $defalt_array – an array with attributes and their values. $attr – an array of attributes that we pass through shortcode.

Is it possible to pass an array in a WordPress shortcode?

Wordpress shortcodes have some painful restrictions in the format of the data which can be passed... That will give you the array passing you want.

How do I write a WordPress shortcode?

Shortcodes are written by providing a handler function. Shortcode handlers are broadly similar to WordPress filters: they accept parameters (attributes) and return a result (the shortcode output). Shortcode names should be all lowercase and use all letters, but numbers and underscores should work fine too.


3 Answers

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

//menu
function 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 target
function 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']
like image 114
Pieter Goosen Avatar answered Sep 25 '22 09:09

Pieter Goosen


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 target

function 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.

like image 37
Wil Avatar answered Sep 24 '22 09:09

Wil


Simple way I use:

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

in shortcode callback, just do:

parse_str( str_replace("&amp;", "&", $attrs['param']), $array);
// var_dump( $array );
like image 39
T.Todua Avatar answered Sep 22 '22 09:09

T.Todua