Skip to content

Instantly share code, notes, and snippets.

@contemplate
Created April 26, 2022 00:35
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save contemplate/5c1909bd1bfcd485cc1bdaf8786f3a80 to your computer and use it in GitHub Desktop.
Save contemplate/5c1909bd1bfcd485cc1bdaf8786f3a80 to your computer and use it in GitHub Desktop.
WooCommerce - Disable guest checkout for certain products when Guest checkout is Enabled globally
/*--------------------------------------
Woocommerce - Disallow Guest Checkout on Certain products
----------------------------------------*/
// Display Guest Checkout Field
add_action( 'woocommerce_product_options_general_product_data', 'woo_add_disable_gc_fields' );
function woo_add_disable_gc_fields() {
global $woocommerce, $post;
echo '<div class="options_group">';
// Checkbox
woocommerce_wp_checkbox(
array(
'id' => '_disable_guest_checkout',
'label' => __('Checkout', 'woocommerce' ),
'description' => __('Disable Guest Checkout', 'woocommerce' )
)
);
echo '</div>';
}
// Save Guest Checkout Field
add_action( 'woocommerce_process_product_meta', 'woo_add_disable_gc_fields_save' );
function woo_add_disable_gc_fields_save( $post_id ){
$woocommerce_checkbox = isset( $_POST['_disable_guest_checkout'] ) ? 'yes' : 'no';
update_post_meta( $post_id, '_disable_guest_checkout', $woocommerce_checkbox );
}
// Disable Guest Checkout on Certain products
add_filter( 'pre_option_woocommerce_enable_guest_checkout', 'disable_guest_checkout_based_on_product' );
function disable_guest_checkout_based_on_product( $value ) {
if ( WC()->cart ) {
$cart = WC()->cart->get_cart();
foreach ( $cart as $item ) {
if ( get_post_meta( $item['product_id'], '_disable_guest_checkout', true ) == 'yes' ) {
$value = "no";
} else {
$value = "yes";
break;
}
}
}
return $value;
}
@contemplate
Copy link
Author

@vdrover
Copy link

vdrover commented Apr 26, 2022

Works prefectly!

@Silver556
Copy link

Awesome, thanks! Is there any way this can be applied to individual product variations? I need to allow guest checkout for an ebook file download, but must disable guest checkout for a LearnDash source.

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