在页面访问中设置WooCommerce产品数量

时间:2016-01-20 作者:Badger

我正在尝试设置访问页面时的产品数量。如果产品不在篮子中,代码可以正常工作并添加正确的数量。然而,如果我有任何东西在篮子里,并刷新它,它会添加另外13个项目。

// add unpaid entries to cart
add_action( \'pre_get_posts\', \'add_entries_to_cart\' );

function add_entries_to_cart() {
    global $woocommerce;

    // Check we are logged in
    if ( is_user_logged_in() ) {

        // Check if we are in admin area
        if ( ! is_admin() ) {
            $user = wp_get_current_user();
            $entries = get_user_meta($user->ID, \'entry_count\', true);
            $entries_paid = get_user_meta($user->ID, \'paid_entries\', true);

            $product_id = 229;
            $quantity = $entries - $entries_paid;

            $found = false;
            //check if product already in cart, get id
            if ( sizeof( $woocommerce->cart->get_cart() ) > 0 ) {
                foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
                    $_product = $values[\'data\'];
                    if ( $_product->id == $product_id ) {
                        // correct quantity
                        unset( $woocommerce->cart->cart_contents[$product_id] );
                        $woocommerce->cart->add_to_cart( $product_id, $quantity );
                        $found = true;
                    }
                }
                // if product not found, add it
                if ( ! $found ) {
                    $woocommerce->cart->add_to_cart( $product_id, $quantity );
                }
            }
            // no product in cart so add it
            else {
                // add to cart
                $woocommerce->cart->add_to_cart( $product_id, $quantity );
            }
        }
    }
}

1 个回复
最合适的回答,由SO网友:Badger 整理而成

我的代码中有一个错误。从这里开始:http://www.sitepoint.com/woocommerce-actions-and-filters-manipulate-cart/

正在更改

// correct quantity
unset( $woocommerce->cart->cart_contents[$product_id] );
$woocommerce->cart->add_to_cart( $product_id, $quantity );

// correct quantity
// Get it\'s unique ID within the Cart
$prod_unique_id = $woocommerce->cart->generate_cart_id( $product_id );
// Remove it from the cart by un-setting it
unset( $woocommerce->cart->cart_contents[$prod_unique_id] );
$woocommerce->cart->add_to_cart( $product_id, $quantity );
已经奏效了。

相关推荐

如何在Functions.php中链接style.css

我是WordPress的新手;我刚开始学习WordPress。我想把风格联系起来。函数中的css。php,但我无法解决这里可能存在的问题。谁能给我指出正确的方向吗?指数php<?php get_header(); ?> <?php if ( have_posts() ) { while ( have_posts() ) { the_post();