Check for user-agent then show only specified contents in WordPress

I have a WordPress website and want to show a specified content to a user who have a specified User-agent. Here is what I’ve done:

<?php
$user_agent = $_SERVER['HTTP_USER_AGENT']; 
if (strpos( $user_agent, 'CostumizedAgent') !== false)
{
echo "<html><body>Show Only this codes</body></html>
}
else
{
// Show normal website
}
?>

In the condition where user agent doesn’t contain CostumizedAgent word, normal website will be shown to the user (a normal wordpress website) but if contains word CostumizedAgent it’ll only echo a specified HTML code to the user. I use this to create a simple secretly content! (I know it’s no the way it should be done :D)

Read More

So, what should I do? Which codes I have to put in else place? Where should I put all the codes to work? (on all pages of website)

Related posts

1 comment

  1. The better way to do that is to create a separate theme for your other user agent. Assuming you want to create a mobile version of your website, this is what you’ll have to put in the functions.php of your desktop (default) theme :

    function change_theme($current_theme) {
        $user_agent = $_SERVER['HTTP_USER_AGENT']; 
        if(strpos( $user_agent, 'CostumizedAgent') !== false) {
            return 'mobile-theme';
        } else {
            return $current_theme;
        }
    }
    add_filter( 'stylesheet', 'change_theme' );
    add_filter( 'template', 'change_theme' );
    

    This will programmaticaly change the theme based on the user agent, and tell WordPress to use the mobile-theme theme if the user agent condition is satisfied.

Comments are closed.