【问题标题】:Wordpress, random product only on home search pageWordpress,仅在首页搜索页面上的随机产品
【发布时间】:2016-04-01 09:55:42
【问题描述】:

我有一个带有页面导航编号的自定义 wordpress 搜索页面,我的客户要求我在第 1 页随机产品而不是其他产品,但主页上随机显示的所有产品不应显示在其他页面上。

对于查询我有这个代码:

$args = array(
  'post_type' => 'products',
  'paged' => ( get_query_var('paged') ? get_query_var('paged') : 1 )
)   

对于随机:

if( $args['paged'] == 1) {
    $args['orderby'] = 'rand';
} else {
    $args['order'] = 'DESC':
}

当我搜索时结果就在那里,而且首页随机性很好,但是由于随机性已经显示在主页上的一些产品也显示在其他页面上(例如:第 2 页)。

目的不是展示已经在首页展示的产品。

我已经做了类似的事情:

if( $page == 1 ) shuffle($r->posts);

但它只打乱第 1 页上的 10 个产品,其他页面上的其他产品从不显示在第 1 页上。

经过一番思考,我认为将前 10 个随机产品存储到 cookie 或会话中,并为其他页面执行 NOT IN?像这样?

if( $args['paged'] == 1 ){
                        $args['orderby'] = 'rand';

                        $r = new Wp_Query($args);
                        $randomFirstPage = wp_list_pluck( $r->posts, 'ID' );
                        print_r($randomFirstPage);
                        setcookie( 'firstPageResults', $randomFirstPage, time()+3600, '/', 'mydomain.com/dev' );

                    }else{
                        $not_in = $_COOKIE['firstPageResults'];
                        $args['NOT IN'] = $not_in;
                        $r = new Wp_Query($args);

                    }

抱歉英语不好,你能帮帮我吗?

谢谢

【问题讨论】:

    标签: php wordpress search random


    【解决方案1】:

    试试这个方法:

    <?php 
    $products1_ids = array();
    $products2_ids = array();
    $allproducts = get_posts(array('post_type' => 'products'));
    
    $p=1; foreach($allproducts as $products) {
        if(is_page(1) && $p<11) {
           $products1_ids[] = $products->ID;
        }
        if(!is_page(1) && $p>10) {
           $products1_ids[] = $products->ID;
        }
    $p++; }
    shuffle($products1_ids);
    shuffle($products2_ids);
    
    
    $post_in = is_page(1) ? $products1_ids : $products2_ids;  
    $products = new WP_Query(array(
        'post_type' => 'products',
        'posts_per_page' => 10,
        'post__in' => $post_in,
    ));
    
    if($products->have_posts()) {
        while($products->have_posts()) { $products->the_post();
           echo '<div class="post">'
               the_title();
           echo '</div>';
        }
    }
    

    希望对你有帮助

    【讨论】:

      【解决方案2】:

      您在上面发布的代码使用$args['NOT IN'] = $not_in;,但根据WP_Query docs,按id 排除帖子的参数是post__not_in

      $query = new WP_Query(
          array('post_type' => 'post', 'post__not_in' => array(2, 5, 12, 14, 20))
      );
      

      那就试试吧:

      $args['post__not_in'] = $not_in;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-11-18
        • 2011-05-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多