register js for a defined page in script-calls.php

2019-09-11 00:38发布

问题:

I have this js code

var shown = true;
var parent = document.querySelector('.parent');
var child = document.querySelector('.child');

parent.addEventListener('mouseenter', function(){
  child.style.opacity = shown ? 0 : 1;
  shown = !shown;
});

The js is related to the following css

* {
  margin: 0;
  padding: 0;
}

.parent {
  width: 100%;
  margin: 10px auto;
  position: relative;
}

.child {
  position: absolute;
  top: 0;
  width: 100%;
  height: 100%;
  display: block;
  overflow: hidden;
  transition: opacity 0.5s linear;
}


p {
  padding: 1em;
}

and html:

<div class="parent">
<img src="http://www.fundraising123.org/files/u16/bigstock-Test-word-on-white-keyboard-27134336.jpg" alt="" width="500px" height="auto" />

<div class="child">
<img src="http://maui.hawaii.edu/tlc/wp-content/uploads/sites/53/2013/11/testing.jpg" alt="" width="500px" height="auto" />
</div>
</div>

The problem is that I use this code for a particular page, not for the entire site and it works just fine except the fact that on any other page (Home, etc) I receive an error telling me that the .parent element is missing. Nothing unusual as long as I don't need it in that page at all.

Uncaught TypeError: Cannot read property 'addEventListener' of null(anonymous function) @ shomz.js:6  

If this helps, in this moment, the js code defined as shomz.js is registered like this:

...
// Main Scripts
function register_js() {

    if (!is_admin()) {
        $url_prefix = is_ssl() ? 'https:' : 'http:';
        // Register 
        wp_register_script('shomz', THB_THEME_ROOT . '/assets/js/plugins/shomz.js', 'jquery', null, TRUE);

        // Enqueue
        wp_enqueue_script('shomz');
        wp_localize_script( 'app', 'themeajax', array( 'url' => admin_url( 'admin-ajax.php' ) ) );
    }
}
...

At this point, in order to avoid defining .parent/.child elements for every single page, I was wondering, is there any possibility to register the js in the script-calls.php file, being active only for a defined page(s) by id for example?

回答1:

Just wrap your script enqueueing function call with an if condition checking whether the current page's id matches the id of the side on which you want the script to be enqueued or not.

// Main Scripts
function register_js() {

    if (!is_admin()) {
        $url_prefix = is_ssl() ? 'https:' : 'http:';

        /* Get id of current page*/
        $page_id     = get_queried_object_id();
        /* Compare the desired page's id with the current page's id, if       they match, enqueue shomz*/
        if(YOUR_ID == $page_id){
            wp_register_script('shomz', THB_THEME_ROOT . '/assets/js/plugins/shomz.js', 'jquery', null, TRUE);
            wp_enqueue_script('shomz');
        }
        wp_localize_script( 'app', 'themeajax', array( 'url' => admin_url( 'admin-ajax.php' ) ) );
    }
}