dongli1887 2017-11-25 06:22
浏览 134
已采纳

WordPress wp_enque_scripts似乎不起作用

I've created a child of a WordPress theme and now I'm trying to insert custom JavaScript into the home page by modifying functions.php of the child. However, my script is not being loaded and I'm not sure why. I've inserted 'echo' statements into the php code and it seems like

add_action( 'wp_enque_scripts', 'video_bg', 10);

fails to call

video_bg()

Here's the functions.php of my child:

<?php


add_action( 'after_setup_theme', 'post_theme_setup' );

if ( !function_exists( 'post_theme_setup' )):
function post_theme_setup(){

    function video_bg() {
        wp_enque_script( 'myVideo', get_stylesheet_directory_uri() . '/JS/filmScript.js', array('jquery'), '1.0.0', false );
        echo '<script>console.log("Script added?")</script>';
    }

    add_action( 'wp_enque_scripts', 'video_bg', 10);
    echo '<script>console.log("Loop Entered")</script>';

}
endif;

And here's what the console is telling me:

Loop Entered                                      (index):1 
JQMIGRATE: Migrate is installed, version 1.4.1    jquery-migrate.min.js?ver=1.4.1&nocache=1:2 

Could anyone please tell me why video_bg() never gets called? Or is the problem in something else?

  • 写回答

1条回答 默认 最新

  • douyou9923 2017-11-25 07:18
    关注

    If the function isn't called when you added it some add_action, there are 2 possible cases: 1. You entered wrong action/filter hook name. 2. Your loaded page doesn't trigger that hook.

    In this case you did the 1st. There is not a hook called: wp_enque_scripts, there is not a function called wp_enque_scripts. Change them to wp_enqueue_scripts.

    add_action( 'wp_enqueue_scripts', 'video_bg', 10);
    add_action( 'after_setup_theme', 'post_theme_setup' );
    
    if ( !function_exists( 'post_theme_setup' )):
    function post_theme_setup(){
    
        function video_bg() {
            wp_enqueue_scripts( 'myVideo', get_stylesheet_directory_uri() . '/JS/filmScript.js', array('jquery'), '1.0.0', false );
            echo '<script>console.log("Script added?")</script>';
        }
    
        add_action( 'wp_enqueue_scripts', 'video_bg', 10);
        echo '<script>console.log("Loop Entered")</script>';
    
    }
    endif;
    

    You can also optimize your code like that:

    add_action( 'after_setup_theme', 'post_theme_setup' );
    
    if ( !function_exists( 'post_theme_setup' )):
    function post_theme_setup(){
        add_action( 'wp_enqueue_scripts', 'video_bg', 10);
        echo '<script>console.log("Loop Entered")</script>';
    
    }
    endif;
    
      function video_bg() {
            wp_enqueue_scripts( 'myVideo', get_stylesheet_directory_uri() . '/JS/filmScript.js', array('jquery'), '1.0.0', false );
            echo '<script>console.log("Script added?")</script>';
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?