wordpressposts

change the value of posts_per_page on mobile screen


I have this code:

$args = array('post_type' => 'development', 'posts_per_page' => 1, 'order' => 'ASC'); 
$loop = new wp_query($args);
while ($loop->have_posts()) : $loop->the_post();

?>
   //html code here
<?php
endwhile;
?>

and I want to change the value of posts_per_page to (-1) on mobile screen to get all posts.

I tried to use wp_is_mobile but I think it returns true when it is a tablet and I don't want that. Any help?


Solution

  • wp_is_mobile checks $_SERVER['HTTP_USER_AGENT'] and cannot distinguish between a phone and a tablet. There are several options for solving the problem:

    1. Use the library https://github.com/serbanghita/mobile-detect
    $detect = new \Detection\MobileDetect;
    $deviceType = ($detect->isMobile() ? ($detect->isTablet() ? 'tablet' : 'phone') : 'computer');
    
    1. Receive posts via Ajax (may affect SEO) by checking the device via javascript:
    if(window.matchMedia('(min-width:1024px)').matches){
        // desktop
    }
    if(window.matchMedia('(max-width:1023px) and (min-width:768px)').matches){
        // tablet
    }
    if(window.matchMedia('(max-width:767px)').matches){
        // mobile
    }
    
    1. Display the same posts in different blocks (seems the worst option), for example:
    <div class="hidden-mobile">
        <!-- posts -->
    </div>
    <div class="visible-mobile">
        <!-- posts -->
    </div>
    
    @media (max-width: 767px) {
      .hidden-mobile {
        display: none;
      }
    }
    @media (min-width: 768px) {
      .visible-mobile {
        display: none;
      }
    }