用 Woocommerce 3 中特定产品类别的产品替换加售

Replace Upsells with products from a specific product category in Woocommerce 3

我有以下情况 - 到目前为止,我一直将追加销售产品自定义设置为 1 对 1,因为无法在管理员中选择产品类别。

现在,在对不再可用的产品进行大清理之后,网站上有许多产品页面带有 1、2 或 3,而不是默认数量的 4 个 Upsell 产品,这破坏了设计。

有没有办法用特定产品类别的产品替换这些加售?

感谢任何帮助。

要用特定产品类别的产品替换 woocommerce 加售,请使用以下代码(您将在其中定义您的产品类别 slug)

add_filter( 'woocommerce_product_get_upsell_ids', 'custom_upsell_ids', 20, 2 );
function custom_upsell_ids( $upsell_ids, $product ){
    // HERE define your product categories slugs in the array
    $product_categories = array( 't-shirts' ); // <=====  <=====  <=====  <=====  <=====

    // Return the custom query
    return wc_get_products( array(
        'status'    => 'publish', // published products
        'limit'     => 4, // 4 products
        'category'  => $product_categories, // Product categories
        'orderby'   => 'rand', // Random order
        'exclude'   => array( $product->get_id() ), // Exclude current product
        'return'    => 'ids', // Query returns only IDs
    ) );
}

代码进入活动子主题(或活动主题)的 function.php 文件。已测试并有效。

The query is set to display 4 products from a specific product category in a random order (excluding the current product).

官方文档: The wc_get_products() and WC_Product_Query