Search code examples
phpwordpresstemplatesmedia-queriesresponsive

Can I load a different template via a media query?


I have a wordpress site and I am adjusting the css for responsiveness on different screen sizes. I changed a template that came with my theme for posts of a certain type. I would like to use the original template on smaller screen sizes. Any suggestions on how I could go about this? Thanks!


Solution

  • Media queries are computed by the browser, whereas templates are computed by the server, so there is no direct way to do this.

    A common way though is to include the various templates on the server side and use media queries to only display the one you want.

    You'd be looking at something like this:

    <div class="mobile">
       <?php get_template_part("content", "mobile"); ?>
    </div>
    
    <div class="desktop">
       <?php get_template_part("content", "desktop"); ?>
    </div>
    

    And then in your CSS:

    .desktop { display: none; }
    
    @media (min-width: 800px) {
      .mobile { display: none; }
      .desktop { display: block; }
    }
    

    This will hide your desktop template on mobile, and vice versa. It will load your desktop template from content-desktop.php and your mobile one from content-mobile.php.

    It's worth noting that while quick and easy, this usually isn't the best way to go about making a responsive website, because you'll be loading your content twice, and will find it a bit harder to maintain down the line. However, it's certainly a fine way to get started in making things responsive.