Using subdomain m.website.com for mobile theme?

You can have a subdomain, but you cannot detect mobile users reliably. And you shouldn’t.

How to use a subdomain with the same content

In your wp-config.php, look at $_SERVER['HTTP_HOST']. If it matches m.example.com, enforce the current domain as main domain with …

const DOMAIN_CURRENT_SITE = 'm.example.com';

… and filter the active theme:

add_filter( 'stylesheet', function( $stylesheet ) {

    if ( 'm.example.com' === DOMAIN_CURRENT_SITE )
        return 'mobile-theme';

    return $stylesheet;
});

Set up redirections for /wp-admin/ and wp-login.php, so authors cannot write on the mobile site.

Why you should not do that

Detecting mobile users is hard work. You cannot trust user agent strings, because they lie, are empty, or they contain malicious code. Never use wp_is_mobile(), this is embarrassingly naïve.

Being on a mobile device doesn’t mean that a small screen or low bandwidth is used.

The separate subdomains are a thing of the past. They were used when browsers could not handle media queries, and mobile were all small and slow. This isn’t true anymore, so please don’t start building a dinosaur.

See also: How to load content per AJAX depending on screen size.

Leave a Comment