• Resolved kovachck

    (@kovachck)


    I was trying to conditionally enqueue a .js file in my themes functions.php file using –

    if(is_home()){add_action( 'wp_enqueue_scripts', 'my_script' );}
    function my_script() {
    	wp_register_script( 'my_script', get_template_directory_uri() . '/js/my_script.js', array( 'jquery' ));
    	wp_enqueue_script( 'my_script' );

    My read on this was that it should load the script on my homepage (which is set to a static front page). However it doesn’t. Nor does is_front_page() work. I removed the if() statement and the script loads on all pages just fine.

    In trying to troubleshoot I came across this –
    echo get_the_ID();
    returns a blank.

    Sure enough, if I try
    if(is_page(”)){add_action( ‘wp_enqueue_scripts’, ‘my_script’ );}`
    the script loads as if the page ID is a blank.

    What am I doing wrong? How are all my page id’s coming up as blanks.

Viewing 3 replies - 1 through 3 (of 3 total)
  • hello kovachck,
    try following to enqueue on home page of your site:

    function my_script() {
      if( is_front_page() )
        {
      wp_register_script( 'my_script', get_template_directory_uri() . '/js/my_script.js', array( 'jquery' ));
      wp_enqueue_script( 'my_script' );
     }
    }
    
    add_action( 'wp_enqueue_scripts', 'my_script' );

    and get_the_ID(); returns The ID of the current item in the WordPress Loop. False if $post is not set. So if you are using it outside wordpress loop you will not get page id.

    Thread Starter kovachck

    (@kovachck)

    Yes that was it cedcommerce…had to move the page_id check inside the function. Thanks so much!

    Hello kovachck,

    Glad to help you, please mark the thread resolved if you don’t have any further query.

    Thanks.

Viewing 3 replies - 1 through 3 (of 3 total)

The topic ‘Trouble conditionally enqueueing a script’ is closed to new replies.