在类别页面上的产品的pre_get_posts - woocommerce

时间:2014-09-17 17:48:28

标签: wordpress woocommerce

我想过滤类别产品上的产品,以便它只显示某位作者或多位作者的产品。

我已经有以下代码了。这适用于过滤产品。显示正确的产品。除了左侧边栏中的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;
}
?>

感谢您的帮助!

3 个答案:

答案 0 :(得分:0)

很棒的家伙。要立即尝试,让你知道。当你得到Woo团队的回答时,你能告诉我吗?

答案 1 :(得分:0)

我的更新解决方案:仍然很脏,因为它修改了Woocommerce的核心文件(2.2.4),但它有效:

pre_get_posts - 钩子中的

我使用以下代码检索要排除的产品的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'] ) ) ) . ')

答案 2 :(得分:0)

可能更好的方法是在查询中设置'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' );
相关问题