在Woocommerce 3中自动将产品添加到购物车

时间:2018-03-29 18:27:17

标签: php wordpress woocommerce cart product

我希望任何访问我的Woocommerce商店的人都能在他的购物车中找到免费产品。我发现这个代码并且它在中工作但在日志中显示了许多php错误

你知道为什么不“干净”吗?

对此有任何帮助。

library(tidyverse)
all_files <- "path/to/root/folder" %>%
    list.files(pattern = "csv", "recursive = TRUE", full.names = "TRUE") %>%
    set_names() %>%
    imap_dfr(~ bind_cols(read_csv(.x), filepath = .y))

伟大的回复后编辑 谢谢,您的代码没有更多错误,但是您可以检查是否可以选择基于SKU“Surprise”的免费产品?再次感谢所有人。

/*
 * AUTOMATICALLY ADD A PRODUCT TO CART ON VISIT
 */
function aaptc_add_product_to_cart() {
    if ( ! is_admin() ) {
        $product_id = 99999;  // Product Id of the free product which will get added to cart
        $found  = false;
        //check if product already in cart
        if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
            foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
                $_product = $values['data'];
                if ( $_product->get_id() == $product_id )
                    $found = true;
            }
            // if product not found, add it
            if ( ! $found )
                WC()->cart->add_to_cart( $product_id );
        } else {
            // if no products in cart, add it
            WC()->cart->add_to_cart( $product_id );
        }
    }
}
add_action( 'init', 'aaptc_add_product_to_cart' );

1 个答案:

答案 0 :(得分:0)

尝试使用template_redirect动作钩子重新访问类似的代码:

add_action( 'template_redirect', 'auto_add_product_to_cart' );
function auto_add_product_to_cart() {
    if ( is_admin() ) return;

    // Product Id of the free product which will get added to cart;
    $product_id = 99999;

    if ( WC()->cart->is_empty() ) 
    {
        // No products in cart, we add it
        WC()->cart->add_to_cart( $product_id ); 
    } 
    else
    {
        $found  = false;

        //check if product already in cart
        foreach ( WC()->cart->get_cart() as $cart_item ) {
            if ( $cart_item['data']->get_id() == $product_id )
                $found = true;
        }

        // if the product is not in cart, we add it
        if ( ! $found )
            WC()->cart->add_to_cart( $product_id ); 
    }
}

代码进入活动子主题(或活动主题)的function.php文件。经过测试并正常工作。

  

注意: init挂钩在这里不正确,不能用于此...