skip to Main Content

How do i set a different product per page for desktop/mobile?

At the moment i have this code in functions.php:

add_filter( 'loop_shop_per_page', 'new_loop_shop_per_page', 15 );

function new_loop_shop_per_page( $cols ) {

    $cols = 15;
    return $cols;
}

But on mobile i want to show 10 products insted of 15 products. Any advice?

3

Answers


  1. You could use the Class here: http://mobiledetect.net/

    require_once 'Mobile_Detect.php';
    
     
    function new_loop_shop_per_page( $cols ) {
        $device = new Mobile_Detect;
        $cols = $device->isMobile() ? 10 : 15;
        return $cols;
    }
    

    or write a detection function yourself using $_SERVER[‘HTTP_USER_AGENT’] filtering for known mobile devices.

    Login or Signup to reply.
  2. You can use wp_is_mobile() – Test if the current browser runs on a mobile device (smart phone, tablet, etc.)

    So you get:

    function filter_loop_shop_per_page( $products ) {
        if ( wp_is_mobile() ) {
            $products = 10;
        } else {
            $products = 15;
        }
    
        // OR shorthand
        $products = wp_is_mobile() ? 10 : 15;
    
        return $products;
    }
    add_filter( 'loop_shop_per_page', 'filter_loop_shop_per_page', 10, 1 );
    
    Login or Signup to reply.
  3. In the WP documentation there is a way to to check the current browser runs on a mobile device or not.

    You can try wp_is_mobile() (I didn’t test it myself.)

    Reference Here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search