Search code examples
wordpresspostssyndication-feed

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


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!


Solution

  • 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.