nested JS Scripts are not included on wordpress page (using wp_enqueue_scripts)
-
I have a problem with wordpress and wp_enqueue_scripts.
I want to include selected scripts only on specific posts. For example: domain.com/post123/ <- script post123.js should be included. And to display the content within the post, I am using shortcodes.
PROBLEM: The scripts of the second wp_enqueue_scripts are not included (regarding the following setup)
functions.php
... //in the functions.php I require require("assets/shortcodes/custom-shortcodes.php"); ...
custom-shortcodes.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');
script-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' );
Everything is working fine until it reaches the wp_enqueue_scripts in the last file (208.php).
The stroop.js is not included in the code and it looks like wordpress is not processing the last wp_enqueue_scripts hook. If I write an “echo ‘test’; in the script_enqueue_stroop() function, there is no response.
I thought it might be a problem with having a nested wp_enqueue_scripts within a wp_enqueue_scripts?
Version 2 And I tried to change the setup just slightly to prevent the nested wp_enqueue script like this:
custom-shortcodes.php (adaption)
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');
Like this the file is included properly but I get this error:
XHR POST domain.com/wp-admin/admin-ajax.php 400 Bad Request
by the way: Everything was working without any problems before I added the is_single(POSTID) …, but the script was loaded on every single page (what is absolutely unnecessary)
Any ideas? I am struggling with this for a few days now and can’t find a working solution. Thanks a lot :-)`
- The topic ‘nested JS Scripts are not included on wordpress page (using wp_enqueue_scripts)’ is closed to new replies.