John Montgomery
John Montgomery

Reputation: 1965

Replace a value in object array

I have the following array :::

WC_Cart Object (
  [cart_contents] => Array (
    [d6f5bb0bbc] => Array (
      [product_id] => 14
      [variation_id] => 325
      [variation] => Array (
        [Your Build] => Windows
      )
      [quantity] => 1

How would I go about replacing ( updating ) [quantity] => 1 to say [quantity] => 3 :::

Any assistance would be appreciated :::

Update >>> More Info. to make things clearer

Below is the hook ( woocommerce_calculate_totals ) I want to access to change values in the printed array above that originates from print_r($this); :::

I'm not sure how to create the function I need to update the value with add_action( 'woocommerce_calculate_totals', 'my_quantity' );

I have worked with arrays & hooks before but this is a bit out of my league :::

// Allow plugins to hook and alter totals before final total is calculated

do_action('woocommerce_calculate_totals', $this);                   

            /** 
             * Grand Total
             *
             * Based on discounted product prices, discounted tax, shipping cost + tax, and any discounts to be added after tax (e.g. store credit)
             */

$this->total = apply_filters('woocommerce_calculated_total', number_format( $this->cart_contents_total + $this->tax_total + $this->shipping_tax_total + $this->shipping_total - $this->discount_total, 2, '.', ''), $this);

Upvotes: 0

Views: 5212

Answers (3)

biziclop
biziclop

Reputation: 14596

There are actions and filters in WordPress, they are different:

http://codex.wordpress.org/Function_Reference/add_action http://codex.wordpress.org/Function_Reference/add_filter

In WooCommerce there are two very similarly named action/filter:

  • woocommerce_calculate_totals action
  • woocommerce_calculated_total filter

woocommerce_calculate_totals actions are called with the cart object, so what you should do (and hopefully should work) is:

add_action( 'woocommerce_calculate_totals', 'my_quantity' );

function my_quantity( $wc_cart ){
  $wc_cart->cart_contents['d6f5bb0bbc']['quantity'] = 3;
}

Upvotes: 0

Joris Ooms
Joris Ooms

Reputation: 12038

First get cart_contents out of the object, then work your way through the arrays:

$wc_cart->cart_contents['d6f5bb0bbc']['quantity'] = 3;

Upvotes: 0

biziclop
biziclop

Reputation: 14596

This is what you wanted?

$wc_cart->cart_contents['d6f5bb0bbc']['quantity'] = 3;

A few examples of accessing arrays and objects:

$object->some_property
$object->{'complex'.'property'.'name'.(2*3)}
$array[12]
$array['hello']
$array[ $array_index*10 ]

Learn more about arrays and objects at:

Upvotes: 7

Related Questions