Skip to content

Instantly share code, notes, and snippets.

@AnanthFlycart
Created June 20, 2024 12:01
Show Gist options
  • Save AnanthFlycart/c67cad896215bb928fcd31b2e0efa304 to your computer and use it in GitHub Desktop.
Save AnanthFlycart/c67cad896215bb928fcd31b2e0efa304 to your computer and use it in GitHub Desktop.
UpsellWP: Custom conditions
/**
* Register custom condition.
*/
add_filter('cuw_conditions', function ($conditions) {
if (empty($conditions['custom']) && class_exists('CUWCustomCondition')) {
$conditions['custom'] = [
'name' => __("Custom Conditions", 'checkout-upsell-woocommerce'),
'group' => __("Custom", 'checkout-upsell-woocommerce'),
'handler' => new CUWCustomCondition(),
'campaigns' => [
'checkout_upsells',
'cart_upsells',
'double_order',
'upsell_popups',
'cart_addons',
//'post_purchase',
//'noc',
//'thankyou_upsells',
],
];
}
return $conditions;
}, 100);
/**
* Handle custom conditions.
*/
add_action('wp_loaded', function () {
if (class_exists('CUWCustomCondition') || !class_exists('\CUW\App\Modules\Conditions\Base')) {
return;
}
/**
* Custom condition handler class.
*/
class CUWCustomCondition extends \CUW\App\Modules\Conditions\Base
{
/**
* Check condition.
*
* @param array $condition Condition data.
* @param array $data Array of minimal cart or order data.
* @return bool
*/
public function check($condition, $data)
{
if (empty($condition['value'])) {
return false;
}
$condition_passed = false;
if ($condition['value'] == 'custom_1') {
// here you can add your own condition and update $condition passed variable.
} elseif ($condition['value'] == 'custom_2') {
// here you can add your another condition and update $condition passed variable.
}
return $condition_passed;
}
/**
* Render condition view file in campaign page.
*
* @param array $data Condition data.
* @param bool $print Echo view or not.
* @return bool|string
*/
public function template($data = [], $print = false)
{
$key = isset($data['key']) ? (int)$data['key'] : '{key}';
$value = !empty($data['condition']['value']) ? $data['condition']['value'] : [];
ob_start();
?>
<div class="condition-method flex-fill">
<select class="form-control optional trigger-change"
name="conditions[<?php echo esc_attr($key); ?>][value]">
<option value="custom_1" <?php if ($value == 'custom_1') echo "selected"; ?>><?php esc_html_e("Condition 1", 'checkout-upsell-woocommerce'); ?></option>
<option value="custom_2" <?php if ($value == 'custom_2') echo "selected"; ?>><?php esc_html_e("Condition 2", 'checkout-upsell-woocommerce'); ?></option>
</select>
</div>
<?php
$html = ob_get_clean();
if ($print) echo $html;
return $html;
}
}
});
@AnanthFlycart
Copy link
Author

You can add your custom condition check code at line number 53 in the above snippet.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment