简体   繁体   English

Wordpress更改了仅适用于移动设备的帖子数限制

[英]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. 我有WP后端设置 - Blog pages show at most设置为20。

I want to override this setting in my PHP in case that the user agent is mobile. 我想在我的PHP中覆盖此设置,以防用户代理是移动的。

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. 然后将新的帖子限制设置为10。

Is it anyway possible? 无论如何可能吗?

Thanks! 谢谢!

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. 这将根据所有循环中$new_limit变量的值覆盖每页的帖子。 If you want to target only the home page, Then you can add if(is_home()) in the condition too. 如果您只想定位主页,那么您也可以在条件中添加if(is_home())

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). 在我想限制帖子总数的页面上,我将$new_limit设置$new_limit值为20(因为我想要每页20个帖子)。 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. 然后限制设置为10,仅限移动设备。

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

Finally, I added this into my WP_Query : 最后,我将其添加到我的WP_Query

    'posts_per_page' => $new_limit,

Works perfectly as far as I tested 就我测试而言,完美地工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM