Skip to content

Instantly share code, notes, and snippets.

@amdrew
Last active August 29, 2015 14:10
Show Gist options
  • Select an option

  • Save amdrew/e5761f53814feed8fee8 to your computer and use it in GitHub Desktop.

Select an option

Save amdrew/e5761f53814feed8fee8 to your computer and use it in GitHub Desktop.
WooCommerce - Add a "prevent purchase" checkbox to product meta and when checked disallows the product from being purchased and removes add to cart buttons
<?php
/**
* Prevent product from being purchased/added to cart, eg with ?add-to-cart=5735 or otherwise
*/
function sumobi_wc_prevent_purchase_validation( $passed, $product_id ) {
$prevent_purchase = get_post_meta( $product_id, '_wc_prevent_purchase', true );
if ( $prevent_purchase ) {
$passed = false;
wc_add_notice( __( 'This product cannot be purchased.', 'woocommerce' ), 'error' );
}
return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'sumobi_wc_prevent_purchase_validation', 10, 2 );
/**
* Add prevent purchase checkbox
*/
function sumobi_wc_prevent_purchase_option() {
global $thepostid;
woocommerce_wp_checkbox(
array(
'id' => 'wc-prevent-purchase',
'name' => '_wc_prevent_purchase',
'wrapper_class' => '',
'label' => 'Prevent Purchase',
'cbvalue' => true,
'value' => get_post_meta( $thepostid, '_wc_prevent_purchase', true )
)
);
}
add_action( 'woocommerce_product_options_pricing', 'sumobi_wc_prevent_purchase_option' );
/**
* Save prevent purchase checkbox
*/
function sumobi_wc_save_prevent_purchase_option( $post_id ) {
if ( isset( $_POST['_wc_prevent_purchase'] ) ) {
update_post_meta( $post_id, '_wc_prevent_purchase', true );
} else {
delete_post_meta( $post_id, '_wc_prevent_purchase' );
}
}
add_action( 'woocommerce_process_product_meta_simple', 'sumobi_wc_save_prevent_purchase_option', 10, 2 );
/**
* Remove add to cart button
*/
function sumobi_wc_remove_add_to_cart_button() {
if ( ! get_post_meta( get_the_ID(), '_wc_prevent_purchase', true ) ) {
return;
}
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
remove_action( 'woocommerce_simple_add_to_cart', 'woocommerce_simple_add_to_cart', 30 );
remove_action( 'woocommerce_grouped_add_to_cart', 'woocommerce_grouped_add_to_cart', 30 );
remove_action( 'woocommerce_variable_add_to_cart', 'woocommerce_variable_add_to_cart', 30 );
remove_action( 'woocommerce_external_add_to_cart', 'woocommerce_external_add_to_cart', 30 );
}
add_action( 'template_redirect', 'sumobi_wc_remove_add_to_cart_button' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment