【问题标题】:pre_get_posts for products on category page - woocommerce类别页面上产品的 pre_get_posts - woocommerce
【发布时间】:2014-11-11 21:02:05
【问题描述】:

我想过滤产品类别中的产品,使其仅显示某个作者或多个作者的产品。

我已经有以下代码。这在过滤产品时起作用。显示正确的产品。除了左侧边栏中的 Woocommerce 过滤器不受过滤器的影响。左侧的过滤器显示了该类别中的所有原始产品(也来自其他用户),因此计数不正确,并且显示了来自被过滤产品的属性。这不应该是这样。我是否必须为过滤器添加另一个 pre_get_posts?

 <?php
function pre_get_posts_by_author( $q ) {


    if ( ! $q->is_main_query() ) return;
    if ( ! $q->is_post_type_archive() ) return;

    $cat_obj = $q->get_queried_object();

    if($cat_obj->name == 'Nieuw')
    {   
        $q->set( 'author_ids',  '2086,2084');   
    }


}

add_action( 'pre_get_posts', 'pre_get_posts_by_author' );


add_filter( 'posts_where', 'author_posts_where', 10, 2 );
function author_posts_where( $where, &$wp_query )
{
    global $wpdb;


    if ( $wp_query->get( 'author_ids' ) ) {
        $where .= ' AND ' . $wpdb->posts . '.post_author IN (' . $wp_query->get( 'author_ids' ) .')';
    }
    return $where;
}
?>

感谢您的帮助!

【问题讨论】:

    标签: wordpress woocommerce


    【解决方案1】:

    执行此操作的更好方法可能是在查询中设置“author__in”参数,该参数将采用查询将返回产品的作者数组。

    function pre_get_posts_by_author( $q ) {
    
    
        if ( ! $q->is_main_query() || !$q->is_post_type_archive() ) return;
    
        $cat_obj = $q->get_queried_object();
    
        if( $cat_obj->name == 'Nieuw' ){
    
            $q->set( 'author__in',  array(2086,2084)); 
    
        }
    
    }
    add_action( 'pre_get_posts', 'pre_get_posts_by_author' );
    

    【讨论】:

      【解决方案2】:

      我更新的解决方案:在修改 Woocommerce 的核心文件 (2.2.4) 时仍然很脏,但它可以工作:

      pre_get_posts-hook 中,我使用以下代码检索要排除的产品的 ID:

      $_SESSION['total_excluded'] = get_objects_in_term( $term_ids, $taxonomies, $args )` 
      

      (参考:http://codex.wordpress.org/Function_Reference/get_objects_in_term

      然后在woocommerce/includes/widgets/class-wc-widget-layered-nav.php我将第258行更改为:

      $count = sizeof( array_diff(array_intersect( $_products_in_term, WC()->query->filtered_product_ids) , $_SESSION['total_excluded'] ) );
      

      woocommerce/includes/widgets/class-wc-widget-price-filter.php 中,新的第 121、136 行是:

      %1$s.ID IN (' . implode( ',', array_map( 'absint', array_diff(WC()->query->layered_nav_product_ids, $_SESSION['total_excluded']  ) ) ) . ')
      

      woocommerce/includes/widgets/class-wc-widget-price-filter.php 中,新的第 123、138 行是:

      %1$s.post_parent IN (' . implode( ',', array_map( 'absint', array_diff(WC()->query->layered_nav_product_ids, $_SESSION['total_excluded'] ) ) ) . ')
      

      【讨论】:

      • 注意:我的分层导航小部件设置为 AND。如果您使用 OR,您必须相应地在第 269 行调整 woocommerce/includes/widgets/class-wc-widget-layered-nav.php 的代码。另外:我不太确定第 94 行的 woocommerce/includes/widgets/class-wc-widget-price-filter.php 中的情况是什么意思。如果您仅使用价格过滤器,是否会出现这种情况?我没有修改那部分,因为它没有改变我的结果。
      猜你喜欢
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 2013-02-24
      • 1970-01-01
      • 2017-11-25
      • 1970-01-01
      • 1970-01-01
      • 2018-07-23
      相关资源
      最近更新 更多