wp_is_mobile()
云策文档标注
概述
wp_is_mobile() 是一个 WordPress 条件标签函数,用于检测当前浏览器是否运行在移动设备(如智能手机、平板电脑)上。它通过检查 HTTP 请求头中的用户代理字符串或 Sec-CH-UA-Mobile 头来返回布尔值 TRUE 或 FALSE。
关键要点
- 函数返回布尔值,TRUE 表示移动设备,FALSE 表示非移动设备。
- 检测基于用户代理字符串,包括 Mobile、Android、Silk/、Kindle、BlackBerry、Opera Mini 和 Opera Mobi 等关键词。
- 从 WordPress 6.4.0 开始,优先检查 Sec-CH-UA-Mobile 请求头以提高准确性。
- 主要用途是优化移动设备资源(如 CPU、内存、带宽),而非检测屏幕宽度或替代 CSS 媒体查询。
- 在主题中使用时,需注意缓存问题:页面缓存必须区分移动和非移动版本,否则可能导致函数失效。
- 适用于创建轻量级移动版本或独特移动体验,但需额外设计响应式规格(如桌面、移动、AMP)。
代码示例
if ( wp_is_mobile() ) {
// 显示移动设备特定内容
} else {
// 显示桌面设备内容
}注意事项
- 函数不检测屏幕宽度,不能替代 CSS 媒体查询或平台特定样式。
- 在公共主题中使用时,确保缓存解决方案支持移动/非移动分离,否则可能破坏功能。
- 移动和桌面版本仍需保持响应式设计,以适应不同设备尺寸。
原文内容
Test if the current browser runs on a mobile device (smart phone, tablet, etc.).
Source
function wp_is_mobile() {
if ( isset( $_SERVER['HTTP_SEC_CH_UA_MOBILE'] ) ) {
// This is the `Sec-CH-UA-Mobile` user agent client hint HTTP request header.
// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Sec-CH-UA-Mobile>.
$is_mobile = ( '?1' === $_SERVER['HTTP_SEC_CH_UA_MOBILE'] );
} elseif ( empty( $_SERVER['HTTP_USER_AGENT'] ) ) {
$is_mobile = false;
} elseif ( str_contains( $_SERVER['HTTP_USER_AGENT'], 'Mobile' ) // Many mobile devices (all iPhone, iPad, etc.)
|| str_contains( $_SERVER['HTTP_USER_AGENT'], 'Android' )
|| str_contains( $_SERVER['HTTP_USER_AGENT'], 'Silk/' )
|| str_contains( $_SERVER['HTTP_USER_AGENT'], 'Kindle' )
|| str_contains( $_SERVER['HTTP_USER_AGENT'], 'BlackBerry' )
|| str_contains( $_SERVER['HTTP_USER_AGENT'], 'Opera Mini' )
|| str_contains( $_SERVER['HTTP_USER_AGENT'], 'Opera Mobi' ) ) {
$is_mobile = true;
} else {
$is_mobile = false;
}
/**
* Filters whether the request should be treated as coming from a mobile device or not.
*
* @since 4.9.0
*
* @param bool $is_mobile Whether the request is from a mobile device or not.
*/
return apply_filters( 'wp_is_mobile', $is_mobile );
}
Hooks
- apply_filters( ‘wp_is_mobile’, bool $is_mobile )
-
Filters whether the request should be treated as coming from a mobile device or not.
Skip to note 4 content
Codex
Example
Skip to note 5 content
bantunes
Basic usage example:
/* Display and echo mobile specific stuff here */ /* Display and echo desktop stuff here */Skip to note 6 content
Tom Rhodes
Note: Whilst caching issues are mentioned in more information for this function it cannot be re-stated enough that any page caching, which does not split itself into mobile and non-mobile buckets, will break this function. If your page caching is global and a desktop device triggers a refresh, the return of this function will always be FALSE until the next refresh. Likewise if a mobile device triggers the refresh, the return will always be TRUE. IF you expect the result of this function to change on a per user basis, ensure that you have considered how caching will affect your code.