Site logo

Archived topic

Prevent loading of sidebar on mobile

3 replies · Started by Clare on February 14, 2019

Viewing posts 1–4 of 4

Hi Tom,

I wonder if you could answer a question for me - is there a way to prevent the Wordpress sidebar loading on mobile? So it's there on desktop, but not on mobile.
I don't mean load and then hide it on mobile with media queries and CSS, using display:none;, or visibility:hidden; etc. This still loads the sidebar and all it's resources, and impacts load time.
What I'm curious about, is if there is a way to not even have the sidebar exist on mobile devices, so it will not be loaded at all, and hence save a ton of load time on mobile. But still have one on desktop.
Thanks so much!
C

Detecting mobile or not on the server side of things isn't very reliable, but you could try this:

function isMobile() {
    return preg_match("/(android|avantgo|blackberry|bolt|boost|cricket|docomo|fone|hiptop|mini|mobi|palm|phone|pie|tablet|up\.browser|up\.link|webos|wos)/i", $_SERVER["HTTP_USER_AGENT"]);
}

add_filter( 'generate_sidebar_layout', function( $layout ) {
    if ( isMobile() ) {
        return 'no-sidebar';
    }

    return $layout;
} );

Let me know :)

Thank you SO much Tom!! You're a star :)

Glad I could help :)

This archived topic is closed to new replies.