javascriptwordpressphp-enqueuewp-enqueue-scripts

WordPress enqueuing a CSS file using JavaScript inside Functions.php


I'm trying to load a CSS file just on mobile.

I made some research and found the the best way to do that is by using JS so here is the code I found:

$( document ).ready(function() {      
var isMobile = window.matchMedia("only screen and (max-width: 760px)");

if (isMobile.matches) {
    //Add your script that should run on mobile here
}
});

Now how do I put the code below inside that code?

wp_enqueue_style( 'custom-css', get_template_directory_uri() . '/responsive.css'    );

Also how do I include it on the Functions.php file.

I tried the following approach but it didn't work out

?>
<script>
$( document ).ready(function() {      
var isMobile = window.matchMedia("only screen and (max-width: 760px)");

if (isMobile.matches) {

wp_enqueue_style( 'custom-css', get_template_directory_uri() . '/responsive.css'    );
    
}
});
</script>
<?php

Solution

  • It's not possible by combining PHP and JavaScript. PHP only runs on the server, and JavaScript only on the client (with some exceptions).

    Use the last parameter of the wp_enqueue_style function to set the media attribute on the <link> tag created by the wp_enqueue_style function. MDN says the following about the media attribute:

    You can also provide a media type or query inside a media attribute; this resource will then only be loaded if the media condition is true.

    and

    This attribute specifies the media that the linked resource applies to. Its value must be a media type / media query. This attribute is mainly useful when linking to external stylesheets — it allows the user agent to pick the best adapted one for the device it runs on.

    Source

    So that means that you can do a media query in the media attribute. And if that media query is a match, then the stylesheet will be loaded.

    <?php
    add_action( 'wp_enqueue_scripts', 'add_responsive_style' );
    function add_responsive_style() {
      wp_enqueue_style( 
        'responsive', // Handle.
        get_template_directory_uri() . '/responsive.css', // Path to file.
        [], // Dependencies.
        false, // Version number.
        'screen and (max-width: 760px)' // <-- Media.
      );
    }
    ?>
    

    This will output:

    <link href="yourtheme/responsive.css" rel="stylesheet" media="screen and (max-width: 760px)">