Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
/*
* This is the contents of $_SESSION
* Array
* (
* [qty] => 3
* [sizes] => Array
* (
* [0] => 10-x-12-x-1
* [1] => 10-x-12-x-1
* [2] => 10-x-12-x-1
* )
*
* [frequency] => 1-month
* [quality] => good
* )
*
* There's only one product with a lot of variations. $this->product is the product itself
* uses get_product( $id );
*/
public function shortcode_summary() {
if( !array_key_exists( 'qty', $_SESSION ) ||
!array_key_exists( 'sizes', $_SESSION ) ||
!array_key_exists( 'frequency', $_SESSION ) ||
!array_key_exists( 'quality', $_SESSION ) ) {
// At least one of them doesn't exist
return;
}
// Let's localize the variables and clean session
$qty = $_SESSION['qty'];
$sizes = $_SESSION['sizes'];
$frequency = $_SESSION['frequency'];
$quality = $_SESSION['quality'];
unset( $_SESSION['qty']);
unset( $_SESSION['sizes']);
unset( $_SESSION['frequency']);
unset( $_SESSION['quality']);
// check whether qty and the number of sizes is the same
if( intval( $qty ) !== count( $sizes ) ) {
return;
}
// let's get the products
$variations = $this->product->get_available_variations();
foreach ($sizes as $size) {
foreach ($variations as $variation) {
if( $variation['attributes']['attribute_pa_size'] === $size &&
$variation['attributes']['attribute_pa_subscription-frequency'] === $frequency &&
$variation['attributes']['attribute_pa_quality'] === $quality
) {
$variation_data = array(
'attribute_pa_size' => $size,
'attribute_pa_subscription-frequency' => $frequency,
'attribute_pa_quality' => $quality
);
WC()->cart->add_to_cart( $this->product->id, 1, $variation['variation_id'], $variation_data );
continue;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment