Home > front end >  If URL contains query string in theme functions
If URL contains query string in theme functions

Time:04-17

I'm trying to write a theme function for my WordPress website.

Basically I would like to include the jQuery library if the the URL has ?download

Because it's the only page where jQuery script exist.. So I'm aiming to remove the library on the header for other pages (making the website loads faster is the ultimate goal here).

URL: /windows/post-name/?download

Is the following code correct?

{
if (isset($_GET['download'])) {
   wp_enqueue_script( 'jquery-lib', get_template_directory_uri() . '/js/jquery.min.js', array(), false, false );
}

CodePudding user response:

Wordpress already comes bundled with jQuery. When you have a script that needs jQuery as a dependency, you pass it into wp_enqueue_script().

Here is an example of enqueing a script that depends on jQuery:

wp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/example.js', array('jquery'), '1.0.0', true );

To read more about dependencies WordPress offers, here is the documentation:

https://developer.wordpress.org/reference/functions/wp_enqueue_script/

CodePudding user response:

If you are sure that no need for jQuery on other pages you can use hook to disable jquery except ?download pages by hook ( for example in functions.php theme file ):

add_action( 'wp_enqueue_scripts', function() {
    
    ( isset( $_GET[ 'download' ] ) ) ? wp_enqueue_script( 'jquery' ) : wp_deregister_script( 'jquery' );
    
}, 99 );
  • Related