Ich versuche, die Menge eines Produkts beim Besuch einer Seite festzulegen. Wenn sich das Produkt nicht im Warenkorb befindet, funktioniert der Code einwandfrei und fügt die richtige Menge hinzu. Wenn ich jedoch etwas im Warenkorb habe und es aktualisiere, werden weitere 13 Elemente hinzugefügt.
// 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 );
}
}
}
}
In meinem Code ist ein Fehler aufgetreten. Von hier: http://www.sitepoint.com/woocommerce-actions-and-filters-manipulate-cart/
Ändern
// correct quantity
unset( $woocommerce->cart->cart_contents[$product_id] );
$woocommerce->cart->add_to_cart( $product_id, $quantity );
Zu
// 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 );
Hat gearbeitet.