Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wp_dequeue_script for child theme to replace script

I have a child theme and I am able to add the script I want to use to replace some theme functions and replace the some of the buttons.

But I cannot remove the old button so they are both showing up on top of each other. How can I remove the parent js script?

here is my function.php for the child theme

function replace_scroll(){
    // Remove the Default JavaScript    
    wp_dequeue_script( 'dp-js' );

    // Add your own script  
    $js_url = get_bloginfo('stylesheet_directory') . '/js';
    wp_enqueue_script('dp',"$js_url/dp1.scripts.js"); 
} 
add_action( 'wp_enqueue_scripts', 'replace_scroll' ); 
like image 583
farmerm3 Avatar asked May 07 '14 01:05

farmerm3


Video Answer


1 Answers

A few issues here to begin with

  • You should be using get_stylesheet_directory_uri() for child themes and get_template_directory_uri() for parent themes instead of the get_bloginfo() functions. Latter is slower and uses the first two functions

  • Scripts and styles should be deregistered AND and dequeued to remove them completely from queue

  • Priority is important. You need to hook your function later to make sure that the styles and scripts are registered before you deregister them, otherwise it won't work.

Solution:

Copy the parent js file to your child theme and open it up and make the necessary changed. Save the file

Now you need to dequeue AND deregister the parent js file and then enqueue you new child theme js file

Example

/*
 * Use any number above 10 for priority as the default is 10 
 * any number after 10 will load after
 */
add_action( 'wp_enqueue_scripts', 'my_custom_scripts', 100 );
function my_custom_scripts()
{
    wp_dequeue_script( 'parent-script-handle' );
    wp_deregister_script( 'parent-script-handle' );
    // Now the parent script is completely removed

    /*
     * Now enqueue you child js file, no need to register if you are not 
     * doing conditional loading
     */
    wp_enqueue_script( 'child-script-handle', get_stylesheet_directory_uri() . '/child-script.js' );
    //Now we have done it correctly
}
like image 125
Pieter Goosen Avatar answered Sep 23 '22 04:09

Pieter Goosen