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
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_stylefunction to set themediaattribute on the<link>tag created by thewp_enqueue_stylefunction. MDN says the following about themediaattribute:and
Source
So that means that you can do a media query in the
mediaattribute. And if that media query is a match, then the stylesheet will be loaded.This will output: