首页 文章

WordPress wp_enque_scripts似乎不起作用

提问于
浏览
0

我创建了一个WordPress主题的孩子,现在我试图通过修改孩子的functions.php将自定义JavaScript插入主页 . 但是,我的脚本没有加载,我不知道为什么 . 我已经将'echo'语句插入到php代码中,它似乎就像

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

没有打电话

video_bg()

这是我孩子的functions.php:

<?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;

这是控制台告诉我的内容:

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

谁能告诉我为什么video_bg()永远不会被调用?或者其他问题是什么?

1 回答

  • 1

    如果在添加一些add_action时未调用该函数,则有两种可能的情况:1 . 您输入了错误的操作/过滤器挂钩名称 . 2.您加载的页面不会触发该挂钩 .

    在这种情况下,你做了第一次 . 没有一个名为:wp_enque_scripts的钩子,没有一个名为wp_enque_scripts的函数 . 将它们更改为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;
    

    您还可以像这样优化代码:

    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>';
        }
    

相关问题