Replace default “Select Option” text in Woocommerc

2019-02-20 18:45发布

问题:

I am just starting out with Woocommerce and have a question about drop down select field for variable products. In woocommerce when nothing is selected on this dropdowns, "Select Option" text is displayed.

I need each dropdown select field option to display a different text when nothing has been selected yet.

I found this code which replaces the standard "Select Option" text with what ever I want, but it does to all dropdowns select fields.

  function custom_woocommerce_product_add_to_cart_text($args){
 $args['show_option_none'] = __( 'Select Framed or Unframed Sizes', 'woocommerce' ); 
  return $args;
}

I noticed that the first drop down select field has an ID which is "type", the 2nd one has an ID of "size".

Can we change the above code and have something along the lines of:

  • if ID = type, then use text A,
  • if ID = size, then use text B?

Also can I force the first drop down list to always show all options?

Lets say my first drop down list has options A,B,C and D:

  • If I select A, the 2nd drop down list will give me 1, 2, 3 as options. I choose 2.
  • If now I try to make another selection in the first field it only shows me A and C and leaves B and D out, as B and D is not available in 1 and 3.

Sounds confusing, but I hope it makes sense.

Any help is appreciated.

回答1:

In woocommerce the attributes IDs (or taxonomy) begin all by pa_ as "product attribute", so:

  • The <select> html tag for "Type" should have: id="pa_type" (but not id="type"),
  • The <select> html tag for "Size" should have: id="pa_size" (but not id="size").

Now you can target each attribute by its taxonomy slug this way:

add_filter( 'woocommerce_dropdown_variation_attribute_options_args', 'dropdown_variation_attribute_options', 10, 1 );
function dropdown_variation_attribute_options( $args ){

    // For attribute "Type"
    if( 'pa_type' == $args['attribute'] )
        $args['show_option_none'] = __( 'Select Framed or Unframed Types', 'woocommerce' );

    // For attribute "Sizes"
    if( 'pa_size' == $args['attribute'] )
        $args['show_option_none'] = __( 'Select Framed or Unframed Sizes', 'woocommerce' );

    return $args;
}

Code goes in function.php file of your active child theme (or active theme).

Tested and works.


You are asking many different questions. Here I answer just one. It's the way on StackOverFlow.

Everything is possible in WooCommerce, depending on your knowledge, skills and time to spend.

Your 2nd question is something advanced, complicated and a bit too broad.