• Resolved deseosuho

    (@deseosuho)


    I’m trying to migrate a functioning web app into my wp site. After reading the using javascript codex, I still haven’t been able to get a simple ‘hello world’ script to run.

    I created a new wp template page with the following php:

    <?php
    function my_scripts_method() {
    
    	wp_register_script(
    		'jsexample',
    		get_template_directory_uri() . '/js/jsexample.js' );
    	wp_enqueue_script('jsexample');
    }
    add_action('wp_enqueue_scripts', 'my_scripts_method');
    ?>
    
    <!-- start site content -->
    <script type="text/javascript" src="<?php get_template_directory_uri(); ?>/js/jsexample.js"></script>
    <?php echo get_template_directory_uri() . '/js/jsexample.js'; ?>

    the echo statement shows me that the url for the script is valid. However for pages based on this template, the javascript file, which simply contains alert('Hello World'); does not run. What am I doing wrong?

Viewing 2 replies - 1 through 2 (of 2 total)
  • You need to call that function before the page is output, and by the time that you’ve gotten to the template part it’s too late.

    The correct way to do this is add that code in the themes functions.php file (or the child theme if you’re doing it the “correct” way with an existing theme). If you only want it for one page, you can wrap it with a call to is_single().

    Thread Starter deseosuho

    (@deseosuho)

    Thank you. That solved my issue. I’m still new to the wp build-order…

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Javascript 'Hello World' in page template’ is closed to new replies.