跨页面按类别显示随机排序的帖子的代码

时间:2018-02-02 作者:Denise

我需要显示在多个类别,有多个页面随机顺序职位。例如,一个汽车类别中有100篇帖子,每个类别页面仅显示20篇帖子,顺序是随机的,但不会跨页面重复。

现在我有下面的代码,但它不起作用-它在每个页面上保持随机性,导致人们看到重复的帖子。

如果我们有办法告诉它重新订购,那就更好了,就像Turboseek或Powerseek一样

add_filter( \'posts_orderby\', \'randomise_with_pagination\' );
function randomise_with_pagination( $orderby ) {
    if( is_category( \'art, asseen, auto, baby, business, cstore, candles, 
cell-phones, closeouts, clothing, collectibles, cosmetics, crafts, 
customer-returns, dollar-store, dvd-video, electronics, fashion-accessories, 
flags, food-grocery, furniture, general-merchandise, gifts, handbags, 
health-beauty, holiday-seasonal, housewares, incense, jewelry, knives, lawn-
garden, leather, licensed, logistics, made-in-usa, military, music, 
novelties, party-greeting-cards, patriotic-items, perfumes, pet-supplies, 
professional-supplies, promotional items, religious, security defense, 
shoes, smoking-products, socks-hosiery, sporting-goods, store-supplies, 
sunglasses, tools-hardware, toys-games, trade-shows, uncategorized, vaping, 
watches\' )  ) {
        // Reset seed on load of initial archive page
        if( ! get_query_var( \'paged\' ) || get_query_var( \'paged\' ) == 0 || 
get_query_var( \'paged\' ) == 1 ) {
            if( isset( $_SESSION[\'seed\'] ) ) {
                unset( $_SESSION[\'seed\'] );
            }
        }

        // Get seed from session variable if it exists
        $seed = false;
        if( isset( $_SESSION[\'seed\'] ) ) {
            $seed = $_SESSION[\'seed\'];
        }

             // Set new seed if none exists
            if ( ! $seed ) {
                $seed = rand();
                $_SESSION[\'seed\'] = $seed;
             }

             // Update ORDER BY clause to use seed
             $orderby = \'RAND(\' . $seed . \')\';
     }
     return $orderby;
 }
我的问题被确定为已经回答了,但它是不同的,因为代码没有跨页面工作-我一定是做错了什么。

1 个回复
SO网友:Nate Gay

如果您看到这些帖子在一个类别的多个页面上重复,那么您的种子可能正在重置。我想知道get_query_var( \'paged\' ) 在您访问的分类页面上。

或者,您可以将种子存储在cookie中,并在每次页面加载时访问它。

Sudo代码段:

$cookie_name = "myseed"
if(!isset($_COOKIE[$cookie_name])) {
    $seed = rand();
    setcookie($cookie_name, $seed);
} else {
    $seed = $_COOKIE[$cookie_name];
}

// Update ORDER BY clause to use seed
$orderby = \'RAND(\' . $seed . \')\';

结束