1

I'm trying to insert Highcharts JS into one of my blog posts.

Inserting the code into the text view didn't work and seemed messy anyway.

I've also tried using wp_register_script() and wp_enqueue_script() in functions.php

global $post;
if( is_page() || is_single() )
    {
        switch($post->post_name) 
        {
            case 'test-post':
                wp_register_script( 'charts', get_template_directory_uri() . '/js/standalone-framework.js', array('jquery'));
                wp_enqueue_script('charts');
                wp_register_script( 'mychart', get_template_directory_uri() . '/js/my-chart.js', array('jquery'));
                wp_enqueue_script('mychart');

Using is_page() in header.php to create an if statement to output the script tags.

<?php if ( is_page('test-post')) { ?>
    <script type='text/javascript' src="<?php bloginfo('template_directory'); ?>/js/standalone-framework.js"></script>
    <script type='text/javascript' src="<?php bloginfo('template_directory'); ?>/js/my-chart.js"></script>
<?php } ?>

Finally I tried using custom fields without much luck either.

What's the most efficient way to include this javascript in only a single post? There are lots of questions and answers with many being fairly old now.

1

Enqueueing scripts has not really changed, the Codex example is fine. In terms of efficiency you are talking about differences in the hundreds of milliseconds, but doing it the right way you get the benefit of the function. Even if the end user was sensitive enough to discern a page loading 0.002 seconds slower, most js is cached after the fact, so you would truly need superpowers.

You seem to be missing an action hook for your functions.php, for the sake of clarity register your scripts in separate functions or a block in the same function. For example:

function scott_highcharts(){
  //register
  wp_register_script( 'charts', get_template_directory_uri() . '/js/standalone-framework.js', array('jquery') );
  wp_register_script( 'mychart', get_template_directory_uri() . '/js/my-chart.js', array('jquery') );

  //enqueue conditional
  if ( is_page( 'test-post' )){
      wp_enqueue_script( 'charts' );
      wp_enqueue_script( 'mychart' );
  }
}
add_action( 'wp_enqueue_scripts', 'scott_highcharts' );
| improve this answer | |

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.