从WooCommerce自定义相关产品输出中排除当前产品

时间:2017-07-23 12:57:42

标签: php wordpress woocommerce product

目的是在产品页面上显示4种产品,但是从过滤器中移除当前产品。目前我正在推销相关品牌和类别的产品,但这也是将现有产品推向相关产品...

Woocommerce的当前related.php文件包含以下内容:

if ( ! $related = $product->get_related( $posts_per_page ) ) {
    return;
}
$brands_array = array(0);
$cats_array = array(0);
$cur_product_id = $product->id; 

// get categories
$terms = wp_get_post_terms( $product->id, 'product_brand' );
$category_terms =  wp_get_post_terms( $product->id, 'product_cat' );
// select only the category which doesn't have any children
foreach ( $terms as $term ) {
    $brands_array[] = $term->term_id;
}
foreach ( $category_terms as $category_term ) {
    $cats_array[] = $category_term->term_id;
}

$final_array = array_merge($brands_array, $cats_array);

$filtered_array = array_filter($final_array, "test_odd");

function test_odd($var)
{
    return($var & 1);
}

var_dump($final_array);

$args = apply_filters( 'woocommerce_related_products_args', array(
    'post_type' => 'product',
    'ignore_sticky_posts' => 1,
    'no_found_rows' => 1,
    'posts_per_page' => 4,
    'columns' => 4,
    'orderby' => $orderby,
    'tax_query' => array(
        array(
            'taxonomy' => 'product_brand',
            'field' => 'id',
            'terms' => $final_array
        ),
    )
));

$products                    = new WP_Query( $args );
$woocommerce_loop['name']    = 'related';
$woocommerce_loop['columns'] = apply_filters( 'woocommerce_related_products_columns', $columns );

if ( $products->have_posts() ) : ?>

    <div class="related products">

        <h2><?php _e( 'Related Products', 'woocommerce' ); ?></h2>
        <?php echo $filtered_array ?>
        <?php woocommerce_product_loop_start();

             while ( $products->have_posts() ) : $products->the_post();

                    wc_get_template_part( 'content', 'product' ); ?>

            <?php endwhile; // end of the loop. ?>

        <?php woocommerce_product_loop_end(); ?>

    </div>

<?php endif;

wp_reset_postdata();

如何从产品页面上显示的产品阵列中过滤当前产品?

由于

1 个答案:

答案 0 :(得分:0)

要排除当前产品,WP_Query中缺少的参数为 'post__not_in' (array) 。所以你的$ args数组将是:

// The current product id (Woocommerce version retro compatible)
$cur_product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id; 

$args = apply_filters( 'woocommerce_related_products_args', array(
    'post_type' => 'product',
    'ignore_sticky_posts' => 1,
    'post__not_in' => array( $cur_product_id ), // <==== HERE
    'no_found_rows' => 1,
    'posts_per_page' => 4,
    'columns' => 4,
    'orderby' => $orderby,
    'tax_query' => array(
        array(
            'taxonomy' => 'product_brand',
            'field' => 'id',
            'terms' => $final_array
        ),
    )
));

$products = new WP_Query( $args );

// . . .