Support » Plugin: WooCommerce » woocommerce email display text according to checkbox value

  • Resolved mgason

    (@mgason)


    I have successfully setup some custom fields on checkout and it all works fine.
    I have a checkbox as one of the fields. ‘my_gift_wrap_checkbox’
    I managed to write code to display text in the orders page (‘yes please!’ or ‘No thank you’) instead of a simple blank or ‘1’
    I can’t figure out how to achieve the same in the email code.
    My code is

    /**
     * Add the field to order emails
     **/
    add_filter('woocommerce_email_order_meta_keys', 'my_woocommerce_email_order_meta_keys');
    
    function my_woocommerce_email_order_meta_keys( $keys ) {
    	$keys['Gift wrap?'] = 'my_gift_wrap_checkbox';
    	$keys['Gift wrap instructions'] = 'my_gift_wrap_field';
    	return $keys;
    }

    Right now if it is checked I get ‘Gift wrap?: 1’
    I want ‘Gift wrap?: Yes please!’
    If not checked it shows ‘Gift wrap?:’
    I want ‘Gift wrap: No thank you.’

    https://wordpress.org/plugins/woocommerce/

Viewing 2 replies - 1 through 2 (of 2 total)
  • solution to this problem was to dump the keys idea altogether. This worked perfectly. Thanks to Ethan Jinks O’Sullivan over on StackExchange

    add_action( "woocommerce_email_after_order_table", "my_woocommerce_email_after_order_table", 10, 1);
    
    function my_woocommerce_email_after_order_table( $order ) {
        $my_gift_wrap_checkbox = get_post_meta( $order->id, "my_gift_wrap_checkbox", true );
        $gift_wrap = $my_gift_wrap_checkbox ? 'Yes please!' : 'No thank you.';
    
        echo '<p><strong>Gift wrap?: </strong>' . $gift_wrap . '</p>';
    
        if ( $my_gift_wrap_checkbox ) {
            echo '<p><strong>Gift wrap instructions: </strong>' . get_post_meta( $order->id, "my_gift_wrap_field", true ) . '</p>';
        }
    
    }
    Caleb Burks

    (@icaleb)

    Automattic Happiness Engineer

    Nice work finding a solution, and thanks for posting back here for others.

    The following is a conditional statement.

    $gift_wrap = $my_gift_wrap_checkbox ? 'Yes please!' : 'No thank you.';

    $my_gift_wrap_checkbox is going to either be 0 or 1 like you experienced earlier. So if it’s 0, then the “else” part of the condition will be assigned to $gift_wrap. If it’s 1, then ‘Yes please!’ is assigned. This is because PHP treats 1 as true, and 0 as false. Then from there on you can use $gift_wrap to display the text to customers.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘woocommerce email display text according to checkbox value’ is closed to new replies.