【问题标题】:Wordpress custom query showing duplicate Results on frontendWordpress 自定义查询在前端显示重复的结果
【发布时间】:2015-01-21 23:58:10
【问题描述】:

我在 woocommerce 网站上进行了自定义搜索查询。 一切看起来都很好。但是,当我搜索 sku 编号之类的内容时,会显示两个搜索结果。

搜索结果示例
示例——http://bxcell.iteratemarketing.com/?s=BE0204&post_type=product

这是我的代码

add_filter('the_posts', 'woo_custom_fields_query');

    function woo_custom_fields_query($posts, $query = false) {
      if (is_search()){
        $noIds = array(0);
          foreach($posts as $post){
              $noIds[] = $post->ID;
          }

          $mPosts = get_post_by_custom_field(get_search_query(), $noIds);      

          if ($mPosts){
              foreach($mPosts as $product_id){
                  $posts[] = get_post($product_id->post_id);                
              }
          }
          return $posts;
      }
      return $posts;
    }

    function get_post_by_custom_field($qrval, $noIds) {
      global $wpdb, $wp_query;

      $pstArr = array();

      $noIdsQrl = implode(",", $noIds);
      $vrvspsts = $wpdb->get_results(
                      "
            SELECT p.post_parent as post_id FROM $wpdb->posts as p
            join $wpdb->postmeta pm
            on p.ID = pm.post_id         
            and pm.meta_value LIKE '%$qrval%'
            join $wpdb->postmeta visibility
            on p.post_parent = visibility.post_id    
            and visibility.meta_key = '_visibility'
            and visibility.meta_value <> 'hidden'
            where 1
            AND p.post_parent <> 0
            and p.ID not in ($noIdsQrl)
            and p.post_status = 'publish'
            group by p.post_parent
            "
      );

      foreach($vrvspsts as $post){
          $noIds[] = $post->post_id;
      }

      $noIdsQrl = implode(",", $noIds);

      $rglprds = $wpdb->get_results(
          "SELECT p.ID as post_id FROM $wpdb->posts as p
          join $wpdb->postmeta pm
          on p.ID = pm.post_id        
          AND pm.meta_value LIKE '%$qrval%' 
          join $wpdb->postmeta visibility
          on p.ID = visibility.post_id    
          and visibility.meta_key = '_visibility'
          and visibility.meta_value <> 'hidden'
          where 1
          and (p.post_parent = 0 or p.post_parent is null)
          and p.ID not in ($noIdsQrl)
          and p.post_status = 'publish'
          group by p.ID

    ");

      $pstArr = array_merge($vrvspsts, $rglprds);
      $wp_query->found_posts += sizeof($pstArr);    
      return $pstArr;
    }

提前致谢!

【问题讨论】:

    标签: php mysql wordpress


    【解决方案1】:

    我认为,您的两个查询逻辑存在问题。您从两个结果中获得合并数组中的重复帖子 ID。

     $pstArr = array_unique(array_merge($vrvspsts, $rglprds));
    

    【讨论】:

      猜你喜欢
      • 2016-04-07
      • 2013-12-27
      • 2016-03-16
      • 2018-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-24
      相关资源
      最近更新 更多