0

I need to pass a php string that is stored in $attr['footer_caption'] inside a shortcode function to a js file where the highcharts are initialized.

$fields = array(

        array(
            'label' => esc_html( 'Footer label' ),
            'description' => esc_html( 'Choose the footer label' ),
            'attr' => 'footer_caption',
            'type' => 'text',
        ),


public static function shortcode_ui_chart( $attr, $content, $shortcode_tag ) {

    $attr = shortcode_atts( array(
        'chart' => null,
        'footer_caption' => null,
    ), $attr, $shortcode_tag );

I've been reading about localize script but couldnt get it to work. Is there a simple way to perfom this? I want the string from that php array in this variable:

    Highcharts.setOptions({
  chart: {
          type: 'column',
          events: {
              load: function () {
                var teste 'WANT TO PASS $attr['footer_caption'] HERE'
                var label = this.renderer.label(teste)
0

You can use the wp_localize_script to pass a variable to your javascript.

Here is an example:

wp_register_script('your_script_name', 'path/to/script.js');
$variables = array (
    'footer_caption' => $attr['footer_caption'],
);
wp_localize_script('your_script_name', 'js_object_name', $variables );
wp_enqueue_script('your_script_name');

Then you can acces to this variable by:

js_object_name.footer_caption
0

Can you post how you tried to use localize_script? Because i use the function often for passing PHP vars to JavaScript and it always worked.

Another way would be to echo the variable in shortcode_ui_chart so you later can use it in your script:

echo '<script type="text/javascript">var footer_caption = "' . $attr['footer_caption'] . '"</script>';

With this code you can use the variable footer_caption in your javascript.

EDIT: See comments for code explanation

var chart1 = Highcharts.chart({
    chart: {
        events: {
            load: function () {
                var caption 'footer_caption'
                var label = this.renderer.label(caption)
            }
        }
    }
});
  • Thanks it worked, but i've got one more problem. The js file always outputs the last value of 'footer_caption' in the footer of all charts – user117473 May 3 '17 at 14:29
  • I don't know Highcharts, but according to their documentation about setting options you can set options global (for all charts) or local (for one specific chart). You are setting the options global, so it affects all charts. You have to set the footer local, if it should only be shown on one chart. – ahendwh2 May 4 '17 at 7:31
  • See answer for js-code with local options – ahendwh2 May 4 '17 at 7:36

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.