Woocommerce:在单一类别上自动将产品添加到购物车

时间:2015-12-04 21:10:57

标签: php wordpress woocommerce

我试图让Woocommerce像这样工作: 一旦用户自动从某个类别购买东西,我想添加一个产品。 怎么做? 以下代码在全球范围内自动访问。

    // add item to cart on visit
add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
    if ( ! is_admin() ) {
        $product_id = 222;
        $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->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 );
        }
    }
}

0 个答案:

没有答案
相关问题