php 如何从 Woocommerce 中的“选择一个选项”更改按钮文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32170575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:48:58  来源:igfitidea点击:

How do I change button text from "Choose an option" in Woocommerce?

phpwordpresswoocommerce

提问by jfoutch

How would I go about changing this PHP code to to change Choose an option based on the id of the select element in the Woocommerce plugin for WordPress? I believe I have found the correct PHP file in wc-template-function.php but my lack of PHP skills is holding me back. Here is what I have so far:

我将如何更改此 PHP 代码以更改根据 WordPress 的 Woocommerce 插件中选择元素的 ID 选择一个选项?我相信我在 wc-template-function.php 中找到了正确的 PHP 文件,但我缺乏 PHP 技能阻碍了我。这是我到目前为止所拥有的:

if ( ! function_exists( 'wc_dropdown_variation_attribute_options' ) ) {

    /**
     * Output a list of variation attributes for use in the cart forms.
     *
     * @param array $args
     * @since 2.4.0
     */
    function wc_dropdown_variation_attribute_options( $args = array() ) {
        $args = wp_parse_args( $args, array(
            'options'          => false,
            'attribute'        => false,
            'product'          => false,
            'selected'         => false,
            'name'             => '',
            'id'               => '',
            'class'            => '',
            'show_option_none' => __( 'Choose an option', 'woocommerce' ),
            'show_option_color' => __( 'Choose a color', 'woocommerce' ),
            'show_option_size' => __( 'Choose a size', 'woocommerce' )
        ) );

        $options   = $args['options'];
        $product   = $args['product'];
        $attribute = $args['attribute'];
        $name      = $args['name'] ? $args['name'] : 'attribute_' . sanitize_title( $attribute );
        $id        = $args['id'] ? $args['id'] : sanitize_title( $attribute );
        $class     = $args['class'];

        if ( empty( $options ) && ! empty( $product ) && ! empty( $attribute ) ) {
            $attributes = $product->get_variation_attributes();
            $options    = $attributes[ $attribute ];
        }

        echo '<select id="' . esc_attr( $id ) . '" class="' . esc_attr( $class ) . '" name="' . esc_attr( $name ) . '" data-attribute_name="attribute_' . esc_attr( sanitize_title( $attribute ) ) . '">';

        if ( $args['show_option_none'] ) {
            echo '<option value="">' . esc_html( $args['show_option_none'] ) . '</option>';
        }
        if ( $args['$id_colors'] ) {
            echo '<option value="">' . esc_html( $args['show_option_color'] ) . '</option>';
        }
        if ( $args['$id_sizes'] ) {
            echo '<option value="">' . esc_html( $args['show_option_size'] ) . '</option>';
        }

        if ( ! empty( $options ) ) {
            if ( $product && taxonomy_exists( $attribute ) ) {
                // Get terms if this is a taxonomy - ordered. We need the names too.
                $terms = wc_get_product_terms( $product->id, $attribute, array( 'fields' => 'all' ) );

                foreach ( $terms as $term ) {
                    if ( in_array( $term->slug, $options ) ) {
                        echo '<option value="' . esc_attr( $term->slug ) . '" ' . selected( sanitize_title( $args['selected'] ), $term->slug, false ) . '>' . apply_filters( 'woocommerce_variation_option_name', $term->name ) . '</option>';
                    }
                }
            } else {
                foreach ( $options as $option ) {
                    // This handles < 2.4.0 bw compatibility where text attributes were not sanitized.
                    $selected = sanitize_title( $args['selected'] ) === $args['selected'] ? selected( $args['selected'], sanitize_title( $option ), false ) : selected( $args['selected'], $option, false );
                    echo '<option value="' . esc_attr( $option ) . '" ' . $selected . '>' . esc_html( apply_filters( 'woocommerce_variation_option_name', $option ) ) . '</option>';
                }
            }
        }

        echo '</select>';
    }
}

You can see where I tried to add show_option_color and show_option_size in to the array and then add if statements for them, but it doesn't seem to be working. I'm not sure how to reference the id of the select element and write the if statement based on if its is the correct select element.

您可以看到我尝试将 show_option_color 和 show_option_size 添加到数组中的位置,然后为它们添加 if 语句,但它似乎不起作用。我不确定如何引用 select 元素的 id 并根据它是否是正确的 select 元素编写 if 语句。

Here is the HTML I'm trying to target.

这是我试图定位的 HTML。

<select id="sizes" class="" name="attribute_sizes" data-attribute_name="attribute_sizes">Want this to say Choose a size</select>

<select id="colors" class="" name="attribute_sizes" data-attribute_name="attribute_sizes">Want this to say Choose a color</select>

variable.php code lines 27 - 38:

variable.php 代码第 27 - 38 行:

<?php foreach ( $attributes as $attribute_name => $options ) : ?>
                    <tr>
                        <td class="label"><label for="<?php echo sanitize_title( $attribute_name ); ?>"><?php echo wc_attribute_label( $attribute_name ); ?></label></td>
                        <td class="value">
                            <?php
                                $selected = isset( $_REQUEST[ 'attribute_' . sanitize_title( $attribute_name ) ] ) ? wc_clean( $_REQUEST[ 'attribute_' . sanitize_title( $attribute_name ) ] ) : $product->get_variation_default_attribute( $attribute_name );
                                wc_dropdown_variation_attribute_options( array( 'options' => $options, 'attribute' => $attribute_name, 'product' => $product, 'selected' => $selected ) );
                                echo end( $attribute_keys ) === $attribute_name ? '<a class="reset_variations" href="#">' . __( 'Clear selection', 'woocommerce' ) . '</a>' : '';
                            ?>
                        </td>
                    </tr>
                <?php endforeach;?>

回答by Josh LaBau

This is a perfect use case for a custom filter! I am first going to describe a method that is not the quickest way, but it is probably the cleanest and easiest to understand for anyone else who might have to read your code. I will also describe a 'dirtier' way that should do the job if you are in a time crunch.

这是自定义过滤器的完美用例!我首先要描述一种方法,它不是最快的方法,但对于可能需要阅读您的代码的任何其他人来说,它可能是最清晰和最容易理解的方法。我还将描述一种“更肮脏”的方式,如果您处于时间紧迫的状态,它应该可以完成这项工作。

Quick Way:

快捷方式:

The place to find where this is displayed is in the file:

找到显示位置的位置在文件中:

/wp-content/plugins/woocommerce/templates/single-product/add-to-cart/variable.php

Around line 27, depending on your version of WooCommerce, you will see something like this line:

在第 27 行左右,根据您的 WooCommerce 版本,您将看到如下内容:

<option value=""><?php echo __( 'Choose an option', 'woocommerce' ) ?>&hellip;</option>

The __() function is running the first parameter through WordPress's translation system using the 'woocommerce' text domain. It is best to preserve the possibility for translation, so we will want to change this text before we send it through the translation function.

__() 函数使用“woocommerce”文本域通过 WordPress 的翻译系统运行第一个参数。最好保留翻译的可能性,因此我们将希望在通过翻译功能发送之前更改此文本。

This line of code happens during a loop that outputs all of the product variation attributes. This allows us to easily see which attribute is being output by looking at the $namevariable.

这行代码发生在输出所有产品变体属性的循环中。这使我们可以通过查看$name变量轻松查看正在输出的属性。

We will need to make a function that takes in the $name variable and outputs a string based on it. It would look something like this:

我们需要创建一个函数,它接受 $name 变量并基于它输出一个字符串。它看起来像这样:

function get_text_for_select_based_on_attribute($attribute) {

// Find the name of the attribute for the slug we passed in to the function
$attribute_name = wc_attribute_label($attribute);

// Create a string for our select
$select_text = 'Select a ' . $attribute_name;

// Send the $select_text variable back to our calling function
return $select_text;
}

Now, before the code on line 27 of variable.php, we can put something like this:

现在,在 variable.php 的第 27 行代码之前,我们可以这样写:

<?php 

  $select_text = get_text_for_select_based_on_attribute($name);

?>

Then, simply swap out 'Choose an option' with your $select_text variable:

然后,只需用您的 $select_text 变量替换“选择一个选项”:

<option value=""><?php echo __( $select_text, 'woocommerce' ) ?>&hellip;</option>

Don't forget to do this all in a template override or your customization will be lost on the next update!

不要忘记在模板覆盖中完成这一切,否则您的自定义将在下次更新时丢失!

http://docs.woothemes.com/document/template-structure/

http://docs.woothemes.com/document/template-structure/

Cleaner Way:

清洁方式:

A better and more extensible way of doing this is to add a custom filter to pass this through. It's a few extra steps, but allows you to easily add further custom logic if you want to override the functionality on a case-by-case basis depending on your product.

一个更好、更可扩展的方法是添加一个自定义过滤器来传递它。这是一些额外的步骤,但如果您想根据您的产品逐案覆盖功能,则允许您轻松添加更多自定义逻辑。

First, make a custom filter with a semantically-meaningful name, and put it somewhere in your functions.php file for the theme:

首先,创建一个具有语义意义名称的自定义过滤器,并将其放在您的functions.php 文件中的某个主题中:

add_filter('variable_product_select_text', 'get_text_for_select_based_on_attribute', 10, 1);

Then, in the variable.php file, instead of just calling the function directly, pass it through your new filter:

然后,在 variable.php 文件中,不是直接调用函数,而是通过新的过滤器传递它:

$select_text = apply_filters('variable_product_select_text', $name);

Setting up custom filters for things like this does take a little bit longer, but you get the advantage of maintainability, since you can stack or turn off functions down the road without needing to further modify your existing code.

为这样的事情设置自定义过滤器确实需要更长的时间,但您可以获得可维护性的优势,因为您可以堆叠或关闭功能,而无需进一步修改现有代码。

Update for WC 2.4

WC 2.4 更新

Version 2.4 of WooCommerce introduces a different way of getting attributes and their associated selects. Since they still have not provided a filter for this, I would recommend overriding the wc_dropdown_variation_attribute_options function using the methods described above. So copy and paste the entire function into your theme's functions.php file starting at the declaration, and add a variable for the select text if it's not a color or size:

WooCommerce 2.4 版引入了一种不同的方式来获取属性及其关联的选择。由于他们仍然没有为此提供过滤器,我建议使用上述方法覆盖 wc_dropdown_variation_attribute_options 函数。因此,从声明开始,将整个函数复制并粘贴到主题的 functions.php 文件中,如果它不是颜色或大小,则为选择文本添加一个变量:

//Don't include the if(!function_exists(...) part.

wc_dropdown_variation_attribute_options($args = array()) {
  // Uses the same function as above, or optionally a custom filter
  $select_text = get_text_for_select_based_on_attribute($args['attribute']);

  wc_dropdown_variation_attribute_options( $args = array() ) {
    $args = wp_parse_args( $args, array(
        'options'          => false,
        'attribute'        => false,
        'product'          => false,
        'selected'         => false,
        'name'             => '',
        'id'               => '',
        'class'            => '',
        'show_option_none' => __( $select_text, 'woocommerce' ),
        'show_option_color' => __( 'Choose a color', 'woocommerce' ),
        'show_option_size' => __( 'Choose a size', 'woocommerce' )
    ) );
// Put the rest of the function here

回答by Marc

I found a way with WC 2.5. Add this to functions.php:

我找到了 WC 2.5 的方法。将此添加到functions.php:

function my_dropdown_variation_attribute_options_html($html, $args){
    $html = str_replace('Choose an option', 'Choose', $html);
    return $html;
}
add_filter('woocommerce_dropdown_variation_attribute_options_html', 'my_dropdown_variation_attribute_options_html', 10, 2);

回答by Joe

I have done this using a combination of the other answers here and it worked well for me.

我已经使用此处其他答案的组合完成了此操作,并且对我来说效果很好。

This was done using WooCoommerce 3.3.5 and assume the filter was added relatively recently.

这是使用 WooCoomerce 3.3.5 完成的,并假设过滤器是最近添加的。

You use the filter for the wc_dropdown_variation_attribute_options()function.

您使用该wc_dropdown_variation_attribute_options()函数的过滤器。

// define the woocommerce_dropdown_variation_attribute_options_args callback 
function filter_woocommerce_dropdown_variation_attribute_options_args( $array ) { 

    // Find the name of the attribute for the slug we passed in to the function
    $attribute_name = wc_attribute_label($array['attribute']);

    // Create a string for our select
    $select_text = 'Select a ' . $attribute_name;

    $array['show_option_none'] = __( $select_text, 'woocommerce' );
    return $array; 
}; 

// add the filter 
add_filter( 'woocommerce_dropdown_variation_attribute_options_args', 'filter_woocommerce_dropdown_variation_attribute_options_args', 10, 1 ); 

Hope this helps someone.

希望这可以帮助某人。

回答by Hooman Askari

There is actually an easier way to customize it.

实际上有一种更简单的方法来定制它。

If you take a look at the core WC file wc-template-functions.php you can see that the array inside wc_dropdown_variation_attribute_options function is actually it's arguments with the following key value pairs:

如果您查看核心 WC 文件 wc-template-functions.php,您可以看到 wc_dropdown_variation_attribute_options 函数中的数组实际上是具有以下键值对的参数:

'options'          => false,
'attribute'        => false,
'product'          => false,
'selected'         => false,
'name'             => '',
'id'               => '',
'class'            => '',
'show_option_none' => __( 'Choose an option', 'woocommerce' )

Now all you need to do is to change the same key value pair in the function in variable.php template file. So I wanted to show the dropdown label instead of the Choose An Option text so I change the fu

现在您需要做的就是在 variable.php 模板文件中的函数中更改相同的键值对。所以我想显示下拉标签而不是选择一个选项文本所以我改变了

wc_dropdown_variation_attribute_options(
    array(
         'options' => $options,
         'attribute' => $attribute_name,
         'product' => $product,
         'selected' => $selected,
         'show_option_none' => wc_attribute_label( $attribute_name )
    )
);

Same goes with other pairs. Hoep this helps. By the way, this only works in WC 2.4+ so be careful.

其他对也一样。希望这有帮助。顺便说一下,这只适用于 WC 2.4+,所以要小心。

回答by tommm

Here's a pretty simple solution for WC >2.4 that avoids rewriting functions and cluttering up your functions.php..

这是 WC > 2.4 的一个非常简单的解决方案,可避免重写函数和使您的 functions.php 变得混乱。

Add the variable.phpfile to your theme (http://docs.woothemes.com/document/template-structure/), and change this (from line 27):

variable.php文件添加到您的主题(http://docs.woothemes.com/document/template-structure/),并更改它(从第 27 行开始):

<?php foreach ( $attributes as $attribute_name => $options ) : ?>
<tr>
    <td class="label"><label for="<?php echo sanitize_title( $attribute_name ); ?>"><?php echo wc_attribute_label( $attribute_name ); ?></label></td>
    <td class="value">
        <?php
            $selected = isset( $_REQUEST[ 'attribute_' . sanitize_title( $attribute_name ) ] ) ? wc_clean( $_REQUEST[ 'attribute_' . sanitize_title( $attribute_name ) ] ) : $product->get_variation_default_attribute( $attribute_name );
            wc_dropdown_variation_attribute_options( array( 'options' => $options, 'attribute' => $attribute_name, 'product' => $product, 'selected' => $selected ) );
            echo end( $attribute_keys ) === $attribute_name ? '<a class="reset_variations" href="#">' . __( 'Clear selection', 'woocommerce' ) . '</a>' : '';
        ?>
    </td>
</tr><?php endforeach;?>

to this:

对此:

<?php 
$variations_arr = array();
foreach ( $attributes as $attribute_name => $options ) : 
    ob_start(); ?>
    <tr>
        <td class="label"><label for="<?php echo sanitize_title( $attribute_name ); ?>"><?php echo wc_attribute_label( $attribute_name ); ?></label></td>
        <td class="value">
            <?php $selected = isset( $_REQUEST[ 'attribute_' . sanitize_title( $attribute_name ) ] ) ? wc_clean( $_REQUEST[ 'attribute_' . sanitize_title( $attribute_name ) ] ) : $product->get_variation_default_attribute( $attribute_name );
            wc_dropdown_variation_attribute_options( array( 'options' => $options, 'attribute' => $attribute_name, 'product' => $product, 'selected' => $selected ) );
            echo end( $attribute_keys ) === $attribute_name ? '<a class="reset_variations" href="#">' . __( 'Clear selection', 'woocommerce' ) . '</a>' : ''; ?>
        </td>
    </tr>
    <?php $variations_ob = ob_get_clean();
    $variations_arr[wc_attribute_label($attribute_name)] = $variations_ob;
endforeach;

foreach ($variations_arr as $name => $ob) {
    echo str_ireplace('choose an option', 'Choose '.$name, $ob );
} ?>

This will replace 'Choose an option' with 'Choose Size', 'Choose Colour' etc. depending on the name of your attribute.

这将根据您的属性名称将“选择一个选项”替换为“选择尺寸”、“选择颜色”等。

回答by Sigma Wadbude

If you're looking to change dropdown text from “Choose an option” in Woocommerce, add following to functions.php file in your theme:

如果您想更改 Woocommerce 中“选择一个选项”中的下拉文本,请将以下内容添加到主题中的 functions.php 文件中:

add_filter('woocommerce_dropdown_variation_attribute_options_args', 'my_change_choose_an_option_text_func', 10, 2);

function my_change_choose_an_option_text_func($args){ 
    $args['show_option_none'] = __( 'New Text', 'your_text_domain' ); 
    return $args; 
}

回答by Savan Dholu

If you are wondering how to replace “Choose an option” with corresponding attribute/variation name, then here's how you can do that. edit variable.php and lookout for the code as the one shown below

如果您想知道如何用相应的属性/变体名称替换“选择一个选项”,那么您可以这样做。编辑 variable.php 并寻找如下所示的代码

Open the variable.php(wp-content/plugins/woocommerce/includes/variable.php) file to your woocommerce and change this (from line 41 to 43): (Remove this 3 line code)

将 variable.php(wp-content/plugins/woocommerce/includes/variable.php) 文件打开到您的 woocommerce 并更改它(从第 41 行到第 43 行):(删除这 3 行代码)

$selected = isset( $_REQUEST[ 'attribute_' . sanitize_title( $attribute_name ) ] ) ? wc_clean( urldecode( $_REQUEST[ 'attribute_' . sanitize_title( $attribute_name ) ] ) ) : $product->get_variation_default_attribute( $attribute_name );
wc_dropdown_variation_attribute_options( array( 'options' => $options, 'attribute' => $attribute_name, 'product' => $product, 'selected' => $selected ) );
echo end( $attribute_keys ) === $attribute_name ? apply_filters( 'woocommerce_reset_variations_link', '<a class="reset_variations" href="#">' . __( 'Clear', 'woocommerce' ) . '</a>' ) : '';

Then add this code

然后添加这个代码

wc_dropdown_variation_attribute_options
array( 'options' => $options,
'attribute' => $attribute_name,
'product' => $product,
'selected' => $selected,
'show_option_none'=> wc_attribute_label( $attribute_name )
) );

It's working all WordPress version Thanks

它适用于所有 WordPress 版本 谢谢

回答by Jonny at Lumos Agency

Updated code, made it for anyone still interested

更新了代码,适合任何仍然感兴趣的人

add_filter( 'woocommerce_dropdown_variation_attribute_options_args', 
fix_option', 10 ); 
function fix_option( $args ) {
    $attr = get_taxonomy( $args['attribute'] ); 
    $label = $attr->labels->name; 
    $fix = str_replace('Product', '', $label); 
    $fix = strtolower($fix); /
    $args['show_option_none'] = apply_filters( 'the_title', 'Select a '.$fix ); 
}