Wordpress change the limit of the number of posts just for mobile

2.9k views Asked by At

I have the WP backend setting - Blog pages show at most set to 20.

I want to override this setting in my PHP in case that the user agent is mobile.

One way that I had in mind is -

    $iphone = strpos($_SERVER['HTTP_USER_AGENT'],"iPhone");
    $android = strpos($_SERVER['HTTP_USER_AGENT'],"Android");
    $ipad = strpos($_SERVER['HTTP_USER_AGENT'],"iPad");
    $berry = strpos($_SERVER['HTTP_USER_AGENT'],"BlackBerry");
    $ipod = strpos($_SERVER['HTTP_USER_AGENT'],"iPod");

Then I thought to do something like

    if ($iphone || $android || $ipad || $ipod || $berry == true)

and then set the new post limit to 10.

Is it anyway possible?

Thanks!

2

There are 2 answers

3
Chirag Swadia On BEST ANSWER
add_action('pre_get_posts','change_limit_mobile');

function change_limit_mobile($query){

    $new_limit = 10;

    $iphone = strpos($_SERVER['HTTP_USER_AGENT'],"iPhone");
    $android = strpos($_SERVER['HTTP_USER_AGENT'],"Android");
    $ipad = strpos($_SERVER['HTTP_USER_AGENT'],"iPad");
    $berry = strpos($_SERVER['HTTP_USER_AGENT'],"BlackBerry");
    $ipod = strpos($_SERVER['HTTP_USER_AGENT'],"iPod");

    if (( $iphone || $android || $ipad || $ipod || $berry ) && $query->is_main_query()){
        set_query_var('posts_per_page',$new_limit);
    }
}

This will override the posts per page based on the value of $new_limit variable in all your loops. If you want to target only the home page, Then you can add if(is_home()) in the condition too.

1
tlt2w On

I managed to solve it in a different way.

On the page where I want to limit the total number of posts I set the $new_limit to be 20 on default (As I want 20 posts per page). Then, I added the condition when it is mobile.

<?php
$new_limit = 20;

$iphone = strpos($_SERVER['HTTP_USER_AGENT'],"iPhone");
$android = strpos($_SERVER['HTTP_USER_AGENT'],"Android");
$ipad = strpos($_SERVER['HTTP_USER_AGENT'],"iPad");
$berry = strpos($_SERVER['HTTP_USER_AGENT'],"BlackBerry");
$ipod = strpos($_SERVER['HTTP_USER_AGENT'],"iPod");

?>

Then the limit is set to 10, only on mobile.

    <?php if ($iphone || $android || $ipad || $ipod || $berry == true){
    $new_limit = 10;}?>

Finally, I added this into my WP_Query:

    'posts_per_page' => $new_limit,

Works perfectly as far as I tested