This shortcode returns the user agent received by WordPress when a browser requests a page. A user agent is a string that identifies the browser making the request.
Usage
[hx_user_agent]
By default, the user agent is wrapped in a block element. For inline use such as within a paragraph, set inline
to true:
[hx_user_agent inline="true"]
Code
function hx_user_agent_shortcode($atts) {
$atts = shortcode_atts(['inline' => false], $atts);
$ua = $_SERVER['HTTP_USER_AGENT'];
if ($atts['inline']) {
return '<span class="user-agent-inline">' . esc_html($ua) . '</span>';
} else {
return '<div class="user-agent-block">' . esc_html($ua) . '</div>';
}
}
add_shortcode('hx_user_agent', 'hx_user_agent_shortcode');
How it works
When someone visits your website, their browser sends a small piece of information called a user agent. This is a text string that identifies the browser, the operating system, and sometimes the device type. The user agent is sent automatically as part of the browser’s HTTP request header.
On the server side, PHP receives the request and populates a global array called $_SERVER
. $_SERVER
is an associative array containing a set of key/value pairs. One of the keys is HTTP_USER_AGENT
, which contains the user agent string sent by the browser.
How to use
To manually install this shortcode, you can add it to functions.php in your theme. However, this is dangerous, and we recommend using a plugin that allows you to create and manage custom bits of code without changing your theme files.
Reference
- UserAgentString.com – displays information about your user agent string.
- shortcode_atts() – Function | Developer.WordPress.org
- PHP: $_SERVER – Manual – information about the $_SERVER array in PHP.
Leave a Reply