• 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 :-)`

Viewing 11 replies - 1 through 11 (of 11 total)
  • Hello!,

    Can you confirm what version of WordPress you are using and if this is being done in a theme or plugin?

    MK

    (@mkarimzada)

    Hi there,

    @flaschenzug22 The second version of your script works fine. The only issue I noticed is the script dependency array, it should be “jquery”.

    function load_custom_shortcode_scripts()
    {
        if (is_admin()) {
            return;
        }
        if (is_single('208')) {
            wp_register_script("gamescript_stroop", get_stylesheet_directory_uri() . '/assets/shortcodes/stroop/stroop.js', array('jquery'));
            wp_enqueue_script('gamescript_stroop');
            wp_localize_script('gamescript_stroop', 'ajaxLoad', array( 'ajaxUrl' => admin_url('admin-ajax.php')));
        }
    }
    add_action('wp_enqueue_scripts', 'load_custom_shortcode_scripts');
    • This reply was modified 2 years, 7 months ago by MK.
    Thread Starter flaschenzug22

    (@flaschenzug22)

    Thanks for your replys.

    @welcher : I am using WordPress 5.8 (the newest version) and it is included in a theme, not a function.

    @mkarimzada : Yes the scripts are included properly. But the ajax is not working anymore. It looks like WordPress is not registering the ajax script correctly.

    The second version throws this error when I try to send a request to the admin-ajax.php file
    XHR POST domain.com/wp-admin/admin-ajax.php 400 Bad Request

    Thanks

    • This reply was modified 2 years, 7 months ago by flaschenzug22.
    Moderator bcworkz

    (@bcworkz)

    In your initial version where you require another file, you’re adding another action callback to an action that has already fired. That’s why it’s not executing. Murtaza’s version is an improvement because everything is in one callback.

    Without seeing the script that makes the Ajax call (or the code that adds the Ajax handler callback), it’s hard to say what the problem is, but usually a bad request error is due to either the wrong “action” value was passed, or the Ajax handler was hooked to the wrong action hook, whose handle is in part composed from the passed “action” value.

    Thread Starter flaschenzug22

    (@flaschenzug22)

    Okay, so I can’t fire an event when it is already fired. That explains why the first version is not working.

    For my second version it doesn’t really make sense.
    I only use one add_action hook.

    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)){
    
            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');

    script-208.php
    //just some random php code

    it should be “jquery”.

    I added my own new version of js-query and removed the original jquery.
    So jquery doesn’t cause the trouble :-).

    Without seeing the script that makes the Ajax call (or the code that adds the Ajax handler callback), it’s hard to say what the problem is, but usually a bad request error is due to either the wrong “action” value was passed, or the Ajax handler was hooked to the wrong action hook, whose handle is in part composed from the passed “action” value.

    Ajax was working without any problems before adding the “function load_custom_shortcode_scripts()” in the custom-shortcodes.php file.

    So any other ideas why there might be a problem?

    Or is there maybe another / a better option to include a php-file / some scripts only for specific posts?

    Thanks a lot

    Moderator bcworkz

    (@bcworkz)

    Impossible to tell for sure from what’s presented. Name collision from script-208.php code maybe? Upon Ajax failure, check browser console and PHP error log for further clues.

    Loading your own version of jQuery can cause conflicts. If you must do so, deregister the default “jquery” then re-register your version as “jquery”. Because core code using “jquery” was developed for the native WP version, there still could be conflicts, but at least you avoid WP loading two different versions at the same time, which certainly will not work.

    FYI, the latest recommendation is to avoid using localize script to pass simple values to JS. It should only be used to actually localize JS to a locale. To pass simple values use wp_add_inline_script() to add a script block that sets your vars. Using localize script would not cause Ajax issues though. There’s nothing functionally wrong with using localize script, it’s only conceptually “wrong”. Just passing on the latest thinking. There remain plenty of examples that still use localize script to pass simple values in WP’s own docs.

    Thread Starter flaschenzug22

    (@flaschenzug22)

    Thanks a lot @bcworkz . Regarding all the suggestions and comments here, I updated the script a litte and changed some things in the code.

    I changed js-jquery to jquery, so wordpress could fall back to jquery if needed (even if i try to get rid of jquery, but for the moment it works).

    While I was changing things I tested one thing:

    custom-shortcodes.php

    function load_custom_shortcode_scripts(){
        if (is_admin()){
            return;
        }
        if(is_single(208)){
            wp_register_script( "gamescript_stroop", get_stylesheet_directory_uri() . '/assets/shortcodes/stroop/stroop.js', array('jquery') );
            wp_enqueue_script( 'gamescript_stroop' );
            wp_localize_script( 'gamescript_stroop', 'ajaxLoad', array( 'ajaxUrl' => admin_url( 'admin-ajax.php' )));
        }
    }
    add_action( 'wp_enqueue_scripts', 'load_custom_shortcode_scripts');
    
    // if moved the require part out of the wp_enqueue_scripts
    require("stroop/stroop.php");

    After placing the require(“”); outside of the wp_enqueue_scripts, the whole thing is running again.

    But that means: The whole stroop.php file is going to be loaded on every single page.

    There must be a simple solution, to just add the files to the specific page/post…?

    FYI, the latest recommendation is to avoid using localize script to pass simple values to JS. It should only be used to actually localize JS to a locale. To pass simple values use wp_add_inline_script() to add a script block that sets your vars.

    Good to know. Am I passing values already? -> [array( ‘ajaxUrl’ => admin_url( ‘admin-ajax.php’ ))]
    I don’t really get the whole concept of localizing scripts for wordpress yet.

    MK

    (@mkarimzada)

    @flaschenzug22 Remember “wp_enqueue_scripts” action is being hooked to “wp_head”. I think a better approach would be separating the “require_once” and “wp_enqueue_scripts”:

    function load_custom_shortcode_scripts()
    {
        if (is_single(208)) {
          
            require_once("stroop/stroop.php");
            
            add_action('wp_enqueue_scripts', function() {
                wp_enqueue_script('gamescript_stroop', get_stylesheet_directory_uri() . '/assets/shortcodes/stroop/stroop.js', array('jquery'), wp_get_theme()->version, false);
                wp_localize_script('gamescript_stroop', 'ajaxLoad', array( 'ajaxUrl' => admin_url('admin-ajax.php')));
            }, 100);
        }
    }
    
    add_action('after_setup_theme', 'load_custom_shortcode_scripts');

    I hope this makes sense. Thank you!

    Thread Starter flaschenzug22

    (@flaschenzug22)

    @mkarimzada I tried to use your code but the stroop.js file is not included on post 208.

    I added an echo after and get a result.
    if (is_single(208)) { echo “test”; … }

    And (to make it a bit more complicated) in the stroop.php I have the following setup:

    // START AJAX CALLS //
    function testscript_stroop() {
         // do something and return something if needed
         die();
    }
    
    add_action("wp_ajax_gamescript_stroop", "testscript_stroop");
    add_action("wp_ajax_nopriv_gamescript_stroop", "testscript_stroop");
    // END AJAX CALLS //
    
    function shortcode_stroop_test() {
        // code for the shortcode
        return $theCodeForTheShortcode;
    }
    add_shortcode('load::stroop-test', 'shortcode_stroop_test');

    And the shortcode within the post is not replaced. Before that it was also working. I guess this is related to the “after_setup_theme” ?

    MK

    (@mkarimzada)

    @flaschenzug22 Here is a good article that shows how WP core loads and adjust the hook to load before or after theme load.
    EDIT: An alternative hook would be wp in your case.

    Also, you could adjust the priority where wp_enqueue_scripts is being hooked or remove it which will default to 10.

    • This reply was modified 2 years, 7 months ago by MK.
    Moderator bcworkz

    (@bcworkz)

    Am I passing values already?

    Yes, the URL returned by admin_url( ‘admin-ajax.php’ ), so your script knows where to send the Ajax request. Another value often passed is a nonce that is in turn sent along with the request as proof the data is coming from a proper source. Failure to be able to verify this nonce on receipt (with check_admin_referer()) could mean there is some kind of malicious activity. Of course you could also pass any other PHP derived value that your JS may need. You may not need such a value now, but the need will arise in the future if you continue to code for WP.

    I second all Murtaza has said about the importance of understanding what order things occur in. It cannot be understated 🙂

Viewing 11 replies - 1 through 11 (of 11 total)
  • The topic ‘nested JS Scripts are not included on wordpress page (using wp_enqueue_scripts)’ is closed to new replies.