Skip to content

Instantly share code, notes, and snippets.

@codeagencybe
Last active July 9, 2018 11:24
Show Gist options
  • Save codeagencybe/06736feef01e1a523b48f280076c42e9 to your computer and use it in GitHub Desktop.
Save codeagencybe/06736feef01e1a523b48f280076c42e9 to your computer and use it in GitHub Desktop.
conditionally show a custom product badge
/**
* @snippet Checkbox to display Custom Product Badge Part 1 - WooCommerce
* @author Fabio Tielen // Code Agency // https://codeagency.be
* @testedwith Woo 3.3+
*/
// -----------------------------------------
// STEP 1. adding a custom checkbox to product edit page
add_action( 'woocommerce_product_options_general_product_data', 'codeagency_add_badge_checkbox_to_products' );
function codeagency_add_badge_checkbox_to_products() {
woocommerce_wp_checkbox( array(
'id' => 'custom_badge',
'class' => '',
'label' => 'Custom Badge Visible'
)
);
}
// -----------------------------------------
// STEP 2. Save checkbox value via custom field
add_action( 'save_post', 'codeagency_save_badge_checkbox_to_post_meta' );
function codeagency_save_badge_checkbox_to_post_meta( $product_id ) {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
if ( isset( $_POST['custom_badge'] ) ) {
update_post_meta( $product_id, 'custom_badge', $_POST['custom_badge'] );
} else delete_post_meta( $product_id, 'custom_badge' );
}
// -----------------------------------------
// STEP 3. Show the custom badge on single product page
add_action( 'woocommerce_single_product_summary', 'codeagency_display_badge', 6 );
function codeagency_display_badge() {
global $product;
if ( get_post_meta( $product->get_id(), 'custom_badge', true ) ) {
echo '<div class="woocommerce-message">FREE SHIPPING!</div>';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment