使用交叉销售产品在WooCommerce谢谢页面上追加销售

时间:2019-12-16 14:21:31

标签: woocommerce

我正在尝试使用订单中产品的Thank You个产品在cross-sell页上进行追加销售。我使用的代码在IF情况下可以正常工作,并且仅在所有产品都具有交叉销售产品的情况下才可以。 示例:如果在Linked Products下未添加Cross-Sells,则该代码将无效。

如果客户购买的一种产品没有交叉销售产品,而另一种产品有交叉销售产品,也会发生同样的事情。该代码仅在订单中的所有产品都有交叉销售产品时有效。

这是我得到的错误,我无法弄清楚:

Warning: array_merge(): Expected parameter 1 to be an array, string given in /wp-content/themes/storefront/functions.php on line 84

这是

Warning: array_unique() expects parameter 1 to be array, null given in /wp-content/themes/storefront/functions.php on line 84

我已经来回尝试了这种方法是否可以与交叉销售产品一起使用。基本上,如果没有交叉销售的产品,我需要它不显示任何内容,如果有,则显示此部分。显然,客户应该能够购买一种或多种产品,而无需添加交叉销售的产品以及已经购买的一种或多种产品,然后-在此基础上,仍然可以看到追加销售部分。

我希望这是合理的(让自己感到困惑)。

这是我正在使用的代码:

add_action( 'woocommerce_thankyou', 'upsell_on_thankyou', 3 ); 
function upsell_on_thankyou( $order_id ){

    $cross_ids = array();
    $order = wc_get_order( $order_id ); 
    $items = $order->get_items();
    foreach ( $items as $item ) {
        $cross_ids = array_unique( array_merge( get_post_meta( $item['product_id'], '_crosssell_ids', true ), $cross_ids )) ;
    }

    if( !empty( $cross_ids ) ) :

        $upsell_cross = new WP_Query( array(
            'post_type' => array( 'product', 'product_variation' ),
            'post_status' => 'publish',
            'post__in' => $cross_ids,
            'orderby' => 'post__in'
        ) );

        if( $upsell_cross->have_posts() ) :
            echo '<section class="upsell-cross-products"><h2>Present for you!</h2><div class="woocommerce columns-3">';

            woocommerce_product_loop_start();

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


                $product = wc_get_product( $upsell_cross->post->ID );

                if( $product->is_type( 'variable' ) ) {
                    continue;
                }

                if( !$product->is_in_stock() ) {
                    continue;
                }

                wc_get_template_part( 'content', 'product' );

            endwhile;

            woocommerce_product_loop_end();

            woocommerce_reset_loop();
            wp_reset_postdata();

            echo '</div></section>';
        endif;
    endif;
}

对于这里我做错了什么,我正在空白。

1 个答案:

答案 0 :(得分:1)

以下get_post_meta不一定返回产品列表:

get_post_meta( $item['product_id'], '_crosssell_ids', true )

如果为空,则不会返回任何内容。而且我实际上不确定如果它具有值,它将如何返回数组,因为您通过将第三个参数设置为true来请求单个值。无论如何,

您首先需要在数组合并之前做准备:

foreach ( $items as $item ) {
$product_crosssell_ids = get_post_meta( $item['product_id'], '_crosssell_ids', true );

if (is_array($product_crosssell_ids) && !empty($product_crosssell_ids)){
$cross_ids = array_unique( array_merge( $product_crosssell_ids, $cross_ids )) ;
}

}