Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save xlplugins/3e32056a23dbe668588a1f932fe34638 to your computer and use it in GitHub Desktop.

Select an option

Save xlplugins/3e32056a23dbe668588a1f932fe34638 to your computer and use it in GitHub Desktop.
Only Allow one bump selection from given array of bump ids
class WFOB_Single_Bump_Selector {
private $bump_ids = array( 3094, 3095 ); // ← Your bump IDs here
public function __construct() {
add_action( 'wfob_before_add_to_cart', array( $this, 'remove_other_bumps' ), 5 );
add_action( 'wp_footer', array( $this, 'uncheck_other_bumps_js' ) );
}
public function remove_other_bumps( $post ) {
$bump_id = absint( $post['wfob_id'] ?? 0 );
if ( ! in_array( $bump_id, $this->bump_ids, true ) ) {
return;
}
$cart = WC()->cart;
if ( ! $cart ) {
return;
}
foreach ( $cart->get_cart() as $cart_key => $cart_item ) {
if ( empty( $cart_item['_wfob_options'] ) ) {
continue;
}
$item_bump_id = absint( $cart_item['_wfob_options']['_wfob_id'] ?? $cart_item['_wfob_options']['bump_id'] ?? 0 );
if ( $item_bump_id !== $bump_id && in_array( $item_bump_id, $this->bump_ids, true ) ) {
// Use WFOB's own remove path: it restores replaced lines *before* removing the bump,
// so the cart is not empty when "replace all" runs for the next bump (raw
// remove_cart_item after stripping _wfob_swap_cart_key left an empty cart).
if ( class_exists( 'WFOB_Common' ) ) {
WFOB_Common::remove_bump_from_cart(
array(
'cart_key' => $cart_key,
'wfob_id' => $item_bump_id,
)
);
} else {
$cart->remove_cart_item( $cart_key );
}
}
}
}
public function uncheck_other_bumps_js() {
if ( ! is_checkout() ) {
return;
}
$bump_ids_js = wp_json_encode( $this->bump_ids );
?>
<script type="text/javascript">
jQuery(function($) {
var bumpIds = <?php echo $bump_ids_js; ?>;
function getBumpId($checkbox) {
var $wrapper = $checkbox.closest('[id^="wfob_wrapper_"]');
if ( $wrapper.length ) {
return parseInt( $wrapper.attr('id').replace('wfob_wrapper_', ''), 10 );
}
return 0;
}
$(document.body).on('change', '#wfob_wrap input[type="checkbox"]', function() {
var $current = $(this);
var currentBumpId = getBumpId($current);
if ( ! $current.is(':checked') || bumpIds.indexOf(currentBumpId) === -1 ) {
return;
}
$('#wfob_wrap input[type="checkbox"]').not($current).each(function() {
var $cb = $(this);
var cbBumpId = getBumpId($cb);
if ( bumpIds.indexOf(cbBumpId) !== -1 && $cb.is(':checked') ) {
$cb.prop('checked', false);
}
});
});
});
</script>
<?php
}
}
new WFOB_Single_Bump_Selector();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment