从功能中筛选产品

问题描述 投票:0回答:1

我创建了以下功能来仅按标签过滤相关产品:

/**
 * Does not filter related products by category and show only based on tags
 */
add_filter( 'woocommerce_product_related_posts_relate_by_category', '__return_false' );

现在我需要从相关产品部分中排除某些产品 ID(大约 30 个)。我需要在这里进行更改吗:

do_action( 'woocommerce_after_single_product_summary_related_products' );

或其他地方可以过滤这些产品 ID?

谢谢

php wordpress function woocommerce product
1个回答
0
投票

我认为您应该删除现有的相关产品输出,并将其替换为非常相似的输出,该输出也接受要排除的自定义 ID。

// First remove and replace the related_product output from its hook.
add_action( 'woocommerce_before_single_product_summary', 'so_47159515_change_related_product' );
function so_47159515_change_related_product(){
    remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_related_products', 20 );
    add_action( 'woocommerce_after_single_product_summary', 'so_47159515_woocommerce_output_related_products', 20 );
}

// Your custom related products output.
function so_47159515_woocommerce_output_related_products( $args = array() ) {
    global $product, $woocommerce_loop;

    if ( ! $product ) {
        return;
    }

    $defaults = array(
        'posts_per_page' => 2,
        'columns'        => 2,
        'orderby'        => 'rand',
        'order'          => 'desc',
    );

    $args = wp_parse_args( $args, $defaults );

    // By default WC excludes the upsell IDs.
    // Our modification will be add extra IDs to this array. 
    $exclude_ids = array( '97', '98', '99' );
    $upsell_ids = $product->get_upsell_ids();
    $exclude_ids = array_merge( $exclude_ids, $upsell_ids );

    // Get visible related products then sort them at random.
    // The third parameter of wc_get_related_products() is now our custom array of IDs.
    $args['related_products'] = array_filter( array_map( 'wc_get_product', wc_get_related_products( $product->get_id(), $args['posts_per_page'], $exclude_ids ) ), 'wc_products_array_filter_visible' );

    // Handle orderby.
    $args['related_products'] = wc_products_array_orderby( $args['related_products'], $args['orderby'], $args['order'] );

    // Set global loop values.
    $woocommerce_loop['name']    = 'related';
    $woocommerce_loop['columns'] = apply_filters( 'woocommerce_related_products_columns', $args['columns'] );

    wc_get_template( 'single-product/related.php', $args );
}

完全未经测试,因此您的里程可能会有所不同。

© www.soinside.com 2019 - 2024. All rights reserved.