Site icon Experience Wordpress Developer Online – Design Develop and Maintenance Support

WooCommerce display custom product badge

In WooCommerce, there are many plugins used to display product badge, messages or notice. Here we display custom product badge by add a checkbox to the product edit page. so it display a conditional badge on single product page based on whether the checkbox is checked or not.

Add below line of code in your theme’s functions.php file of your active child theme (or theme) and save the file.


//  Add new checkbox to product edit page (General tab)
  
add_action( 'woocommerce_product_options_general_product_data', 'add_badge_checkbox_to_products' );        
  
function add_badge_checkbox_to_products() {           
woocommerce_wp_checkbox( array( 
'id' => 'custom_badge', 
'class' => '', 
'label' => 'Show Custom Badge'
) 
);      
}
  
// Save checkbox via custom field
  
add_action( 'save_post', 'save_badge_checkbox_to_post_meta' );
  
function 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' );
}


//  Display badge at single product page if checkbox checked
  
add_action( 'woocommerce_single_product_summary', 'display_badge_if_checkbox', 6 );
  
function display_badge_if_checkbox() {
    global $product;     
    if ( get_post_meta( $product->get_id(), 'custom_badge', true ) ) {
        echo '
CUSTOM BADGE!
'; } }
Exit mobile version