Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save davebonds/00a17329633fffc21a550f40099d226a to your computer and use it in GitHub Desktop.
Save davebonds/00a17329633fffc21a550f40099d226a to your computer and use it in GitHub Desktop.
<?php
add_filter( 'woocommerce_add_cart_item_data', 'add_cart_item_data', 10, 2 );
/**
* Add sem-ad-budget field value to the cart item data.
*
* @param array $cart_item_data Data for cart item.
* @param int $product_id The product ID.
*/
public function add_cart_item_data( $cart_item_data, $product_id ) {
global $woocommerce;
// Check if value was posted then set cart item meta.
if ( isset($_POST[ 'sem-ad-budget' ]) ) {
$cart_item_data['sem-ad-budget'] = $_POST['sem-ad-budget'];
}
return $cart_item_data;
}
add_filter( 'woocommerce_get_cart_item_from_session', 'get_cart_items_from_session', 1, 3 );
/**
* Get sem-ad-budget cart meta value and add to session data.
*
* @param array $session_data Item to add value to.
* @param array $values Cart key values.
* @param string $key Cart key.
* @return array $session_data The item.
*/
public function get_cart_items_from_session( $session_data, $values, $key ) {
// Check if value is in cart values then add to session_data.
if ( array_key_exists( 'sem-ad-budget', $values ) ) {
$session_data[ 'sem-ad-budget' ] = $values['sem-ad-budget'];
}
return $session_data;
}
add_filter( 'woocommerce_get_item_data', 'display_ad_budget_in_cart', 10, 2 );
/**
* Add and display sem-ad-budget $item meta to cart $data array.
*
* @param array $data Data for all cart items.
* @param array $item The item.
* @return array $data Data for all cart items.
*/
public function display_ad_budget_in_cart( $data, $item ) {
// Check if item meta is set then add to cart data array.
if ( isset( $item['sem-ad-budget'] ) ) {
$data[] = array(
'name' => 'Monthly Ad Budget',
'value' => '$' . $item['sem-ad-budget']
);
}
return $data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment