[wp-hackers] Hack for wp_localize_script

andré renaut andre.renaut at gmail.com
Thu Jan 29 23:47:09 GMT 2009


Hello,

wp_localize_script only support array with one level, for translation
purpose.
However, i need to convert a php array (multiple levels) into a javascript
array.

When i try to use an array into an array with wp_localize_script, i get
toto:"Array"...

So i propose the following hack into wp-includes/class.wp-scripts.php for
function print_scripts_l10n()

  48          $eol = '';
  49          foreach ( $this->registered[$handle]->extra['l10n'][1] as $var
=> $val ) {
  50              if ( 'l10n_print_after' == $var ) {
  51                  $after = $val;
  52                  continue;
  53              }
  54              echo "$eol\t\t$var: \"" . js_escape( $val ) . '"';
  55              $eol = ",\n";
  56          }

Becomes

  48          $eol = "\t\t";
  49          foreach ( $this->registered[$handle]->extra['l10n'][1] as $var
=> $val ) {
  50              if ( 'l10n_print_after' == $var ) {
  51                  $after = $val;
  52                  continue;
  53              }
  54              echo "$eol$var: " . $this->print_scripts_l10n_val($val);
  55              $eol = ",\n\t\t";
  56          }

and a new function

function print_scripts_l10n_val($val0,$before="")
{
    if (is_array($val0))
    {
        $eol = "\t\t";
        $text =  "{\n\t$before";
        foreach($val0 as $var => $val)
        {
            $text .=  "$eol$var: " . $this->print_scripts_l10n_val($val,
"\t" . $before );
            $eol = ",\n$before\t\t\t";
        }
        $text .= "\n\t\t$before}";
    }
    else
    {
        $text = '"' . js_escape( $val0 ) . '"';
    }
    return $text;
}

by the way, i do not understand the test "if ( 'l10n_print_after' == $var )"
and the related code

what do you think ?


More information about the wp-hackers mailing list