|
/** |
|
* Add upsell options to cart items on variable prices options |
|
*/ |
|
add_action( 'edd_checkout_cart_item_title_after', function( $item, $key ){ |
|
//Register JS -- probably should do this earlier |
|
wp_register_script( 'cwp-cart', get_stylesheet_directory_uri() . '/assets/js/cart.js', [ 'jquery' ] ); |
|
$id = $item[ 'id' ]; |
|
|
|
//check if we have variable prices, else bail |
|
if( edd_has_variable_prices( $id ) ){ |
|
|
|
//load the JS we need. |
|
wp_enqueue_script( 'cwp-cart' ); |
|
|
|
//find current price and all prices |
|
$cart = edd_get_cart_content_details(); |
|
$current_price = $cart[ $key ][ 'price' ]; |
|
|
|
$prices = edd_get_variable_prices( $id ); |
|
|
|
foreach ( $prices as $price_id => $price ){ |
|
if( isset( $price[ 'index' ] ) && is_numeric( $price[ 'index' ] ) ){ |
|
$price_id = $price[ 'index' ]; |
|
} |
|
|
|
$variant_price = (float) $price[ 'amount'] ; |
|
|
|
//don't show same or lower price options |
|
if( $variant_price == $current_price || $variant_price < $current_price ){ |
|
continue; |
|
} |
|
|
|
//output the upsells |
|
$nonce = wp_create_nonce( $price_id . $id ); |
|
printf( '<div><a class="cwp-cart-change" data-price="%d" data-id="%d" data-nonce="%s" data-key="%s">Change To %s License <span>%s</span></a></div>', |
|
esc_attr( $price_id ), |
|
esc_attr( $id ), |
|
esc_attr( $nonce ), |
|
esc_attr( $key ), |
|
esc_html( $price[ 'name' ] ), |
|
edd_sanitize_amount( $price[ 'amount' ] ) ); |
|
} |
|
|
|
} |
|
|
|
}, 10, 2 ); |
|
|
|
|
|
/** |
|
* AJAX callback for upsells |
|
*/ |
|
add_action( 'wp_ajax_cwp_change_price', 'cwp_sf_child_change_price' ); |
|
add_action( 'wp_ajax_nopriv_cwp_change_price', 'cwp_sf_child_change_price' ); |
|
function cwp_sf_child_change_price(){ |
|
if( isset( $_POST[ 'id' ], $_POST[ 'price' ], $_POST[ 'nonce' ], $_POST[ 'key' ] ) ){ |
|
$cart_key = absint( $_POST[ 'key' ] ); |
|
$price_id = absint( $_POST[ 'price' ] ); |
|
$id = absint( $_POST[ 'id' ] ); |
|
$verified = wp_verify_nonce( $_POST[ 'nonce' ], $price_id . $id ); |
|
if( $verified ){ |
|
$added = edd_add_to_cart( $id, [ 'price_id' => $price_id ] ); |
|
if( $added ) { |
|
edd_remove_from_cart( $cart_key ); |
|
} |
|
|
|
} |
|
|
|
} |
|
|
|
} |