Joe Bloggs
Joe Bloggs

Reputation: 1462

Woocommerce custom fields - Select field - how to do a blank placeholder

I have created a cutom field in woocommerce general tab just below the price:

function woo_add_custom_general_fields() {

  global $woocommerce, $post;

  echo '<div id="wc-after-price">';

     woocommerce_wp_select( 
             array( 
                  'id'      => '_select', 
                  'label'   => __( 'Price Label', 'woocommerce' ), 
                  'options' => array(
                    'blank'         => __( 'Choose one or leave blank', 'woocommerce' ),
                    'Per 50 Words'  => __( 'Price is per 50 words', 'woocommerce' ),
                    'Per 100 Words' => __( 'Price is per 100 words', 'woocommerce' ),
                    'Per Page'      => __( 'Price is per page', 'woocommerce' )
                    )
                 )
      ); 

  echo '</div>';

}

My save function is as follows:

function woo_add_custom_general_fields_save( $post_id ){

    $woocommerce_select = $_POST['_select'];
    if( !empty( $woocommerce_select ) )
        update_post_meta( $post_id, '_select', esc_attr( $woocommerce_select ) );

}

Everything is working well when showing the output, but I am struggling to figure out how to NOT SHOW the first option "blank".

The first option in my dropdown 'blank' => __( 'Choose one or leave blank', 'woocommerce' ), is basically just a placeholder. My dropdown selection is not mandatory, so it could be left blank.

Currently, if I leave the dropdown untouched, it'll show "blank" on the output.

How can I achieve to keep this option only as a placeholder and not show any output at all?

Upvotes: 0

Views: 2976

Answers (1)

Dhaval Shah
Dhaval Shah

Reputation: 375

You can keep the value as an empty string '' instead of blank.

function woo_add_custom_general_fields() {

  global $woocommerce, $post;

  echo '<div id="wc-after-price">';

     woocommerce_wp_select( 
             array( 
                  'id'      => '_select', 
                  'label'   => __( 'Price Label', 'woocommerce' ), 
                  'options' => array(
                    ''         => __( 'Choose one or leave blank', 'woocommerce' ),
                    'Per 50 Words'  => __( 'Price is per 50 words', 'woocommerce' ),
                    'Per 100 Words' => __( 'Price is per 100 words', 'woocommerce' ),
                    'Per Page'      => __( 'Price is per page', 'woocommerce' )
                    )
                 )
      ); 

  echo '</div>';

}

Upvotes: 1

Related Questions