Execute PHP based on screen size

2019-09-29 04:32发布

问题:

I have a directory site with an amazing homepage map, but unfortunately it doesn't load so well on mobile devices. The WordPress theme was setup to use a slider or map, but I'd like to display the slider on mobile devices and maps on desktops. I think this is the code to manipulate this:

 <?php

        ////////////////////////////////////////
        //// WHAT SLIDER ARE WE USING
        ////////////////////////////////////////

        if(ddp('home_slider') == 'Map') {

            get_template_part('includes/slider/markup', 'map');

        } else {

            if(function_exists('putRevSlider')) { putRevSlider(ddp('home_slider_alias')); }  ?>

            <script type="text/javascript">

                jQuery(document).ready(function() { _sf_send_user_to_listings = true; });

            </script>

        <?php  }

    ?>

I understand PHP has no concept of screen size. I also read once JavaScript or jQuery is mixed with the PHP, the server side stops all together and no more PHP can be processed. Perhaps my question - if I used CSS to display a slider on mobile devices, will the device still load the map behind the scenes? And vice versa, will the desktop load both a map and slider but only display one to the user? If the mobile devices are forced to load both, the crash will still occur from the map issue. (By the way, the developer wrote the map to process pins and clustering on the client side, so that's why it crashes apparently.)

If I can accomplish this using CSS, how would I go about changing the above PHP? I'm very new to PHP and server side programming all together. I'm assuming the ddp has something to do with the theme settings, because I'm currently able to select a map or slider (not both).

回答1:

First Option: One way this could be achieved would be using Ajax to detect with Javascript the screen size before asking the server for the content. You can use screen.availWidth or screen.availHeight to detect the screen sizes, and like you would with @media queries in css, base your course of action to take.

Here's a link to the standard screen sizes you would check for: CSS Tricks = Media Queries for Standard devices

After your Javascript uses the proper logic, you would use Ajax to load your content.

If AJAX isn't your thing or your content is too heavy for Ajax exchanges - Second option: have an intermediary html page with Javascript script that does the same logic prescribed above, and then redirects the user to a respective page: the full map page or a mobile version. This method would probably be the better option since your users wouldn't have to wait for Ajax actions. Here's a link for redirecting with Javascript: Redirecting with Javascript