wp_is_mobile()

check wp_is_mobile(): bool

Kiểm tra xem trình duyệt hiện tại có chạy trên thiết bị di động không (điện thoại thông minh, máy tính bảng, v.v.).

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

Hàm wp_is_mobile() phát hiện thiết bị dựa trên giá trị của HTTP_USER_AGENT (không liên quan đến kích thước màn hình).

wp_is_mobile trả về true hoặc false dựa trên giá trị của $_SERVER['HTTP_USER_AGENT'].

  1. Nếu $_SERVER['HTTP_USER_AGENT'] chứa từ khóa Mobile (Android, iOS, ...) hoặc Tablet, thì hàm sẽ trả về true.
  2. Nếu không chứa các từ khóa trên, hàm sẽ trả về false.
  3. Nếu $_SERVER['HTTP_USER_AGENT']null, hàm cũng trả về false.
Ví dụ 1: Kiểm tra "Mobile" hoặc "Desktop"
<?php if ( wp_is_mobile() ) : ?>
	/* Display and echo mobile specific stuff here */
<?php else : ?>
	/* Display and echo desktop stuff here */
<?php endif; ?>