首页 > 解决方案 > wordpress 页面中不包含嵌套的 JS 脚本(在 functions.php 中使用 wp_enqueue_scripts)

问题描述

我对 wordpress 和 wp_enqueue_scripts 有疑问。

我只想在特定帖子中包含选定的脚本。例如:domain.com/post123/ <- 脚本 post123.js 应该包括在内。为了在帖子中显示内容,我使用了简码。

问题:不包括第二个 wp_enqueue_scripts的脚本(关于以下设置)

函数.php

...
//in the functions.php I require 
require("assets/shortcodes/custom-shortcodes.php");
...

自定义简码.php

function load_custom_shortcode_scripts(){
    if(is_single(208)) require("files-208/script-208.php");
    // others might follow
}

add_action( 'wp_enqueue_scripts', 'load_custom_shortcode_scripts');

脚本 208.php

 function script_enqueue_stroop() {   
       wp_register_script( "gamescript_stroop", get_stylesheet_directory_uri() . '/assets/shortcodes/stroop/stroop.js', array('js-jquery') );

       wp_localize_script( 'gamescript_stroop', 'ajaxLoad', array( 'ajaxUrl' => admin_url( 'admin-ajax.php' )));

       wp_enqueue_script( 'gamescript_stroop' );
}
add_action( 'wp_enqueue_scripts', 'script_enqueue_stroop' );

一切正常,直到它到达最后一个文件(208.php)中的 wp_enqueue_scripts。

stroop.js 不包含在代码中,看起来 wordpress 没有处理最后一个 wp_enqueue_scripts 挂钩。如果我在 script_enqueue_stroop() 函数中写了一个 "echo 'test'; ,则没有响应。

我认为在 wp_enqueue_scripts 中嵌套 wp_enqueue_scripts 可能是个问题?

版本 2 我尝试稍微更改设置以防止像这样嵌套 wp_enqueue 脚本:

custom-shortcodes.php(适应)

function load_custom_shortcode_scripts(){
    if(is_single(208)){

        wp_register_script( "gamescript_stroop", get_stylesheet_directory_uri() . '/assets/shortcodes/stroop/stroop.js', array('js-jquery') );
        wp_enqueue_script( 'gamescript_stroop' );
        wp_localize_script( 'gamescript_stroop', 'ajaxLoad', array( 'ajaxUrl' => admin_url( 'admin-ajax.php' )));
        
       require("files-208/script-208.php");
    }
    // others might follow
}

add_action( 'wp_enqueue_scripts', 'load_custom_shortcode_scripts');

像这样,文件被正确包含,但我收到此错误:

XHR POST domain.com/wp-admin/admin-ajax.php 400 Bad Request

顺便说一句:在我添加 is_single(POSTID) ...之前,一切正常,但脚本已加载到每个页面上(绝对没有必要)

有任何想法吗?我已经为此苦苦挣扎了几天,找不到可行的解决方案。非常感谢 :-)

标签: phpajaxwordpresswp-enqueue-scripts

解决方案


推荐阅读