WordPress 在 Functions.php 中使用 JavaScript 排队 CSS 文件

WordPress enqueuing a CSS file using JavaScript inside Functions.php

我正在尝试仅在移动设备上加载 CSS 文件。

我做了一些研究,发现最好的方法是使用 JS,所以这是我找到的代码:

$( 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
}
});

现在如何将下面的代码放入该代码中?

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

还有如何将它包含在 Functions.php 文件中。

我尝试了以下方法,但没有成功

?>
<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

组合 PHP 和 JavaScript 是不可能的。 PHP 仅在服务器上运行,JavaScript 仅在客户端运行(有一些例外)。

使用wp_enqueue_style函数的最后一个参数设置wp_enqueue_style函数创建的<link>标签的media属性。 MDN 对 media 属性的描述如下:

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.

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

这意味着您可以在 media 属性中进行媒体查询。如果该媒体查询匹配,则将加载样式表。

<?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.
  );
}
?>

这将输出:

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