web-dev-qa-db-fra.com

Comment modifier le texte du bouton dans "Choisissez une option" dans Woocommerce?

Comment changer le code PHP en choisissant Choisir une option en fonction de l'id de l'élément select dans le plug-in Woocommerce pour WordPress? Je pense avoir trouvé le bon fichier PHP dans le fichier wc-template-function.php, mais mon manque de compétences PHP me retient. Voici ce que j'ai jusqu'à présent:

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>';
    }
}

Vous pouvez voir où j'ai essayé d'ajouter show_option_color et show_option_size dans le tableau, puis d'ajouter des instructions if, mais cela ne semble pas fonctionner. Je ne sais pas comment référencer l'id de l'élément select et écrire l'instruction if en fonction de si c'est l'élément select correct.

Voici le code HTML que je tente de cibler.

<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>

lignes de code 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;?>
8
jfoutch

C'est un cas d'utilisation parfait pour un filtre personnalisé! Je vais d’abord décrire une méthode qui n’est pas la méthode la plus rapide, mais qui est probablement la plus propre et la plus facile à comprendre pour toute autre personne susceptible de lire votre code. Je vais également décrire une méthode plus "sale" qui devrait faire l'affaire si vous êtes dans une pénurie de temps.

Façon rapide:

L'endroit où trouver ceci est affiché est dans le fichier:

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

Autour de la ligne 27, selon votre version de WooCommerce, vous verrez quelque chose comme cette ligne:

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

La fonction __ () exécute le premier paramètre via le système de traduction de WordPress à l'aide du domaine de texte 'woocommerce'. Il est préférable de conserver la possibilité de traduction. Nous voudrons donc modifier ce texte avant de l'envoyer via la fonction de traduction. 

Cette ligne de code se produit pendant une boucle qui génère tous les attributs de la variation du produit. Cela nous permet de voir facilement quel attribut est affiché en regardant la variable $ name.

Nous devrons créer une fonction qui prend la variable $ name et génère une chaîne basée sur celle-ci. Cela ressemblerait à ceci:

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;
}

Maintenant, avant le code de la ligne 27 de variable.php, on peut mettre quelque chose comme ceci:

<?php 

  $select_text = get_text_for_select_based_on_attribute($name);

?>

Ensuite, permutez simplement 'Choisissez une option' avec votre variable $ select_text:

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

N'oubliez pas de faire tout cela dans un remplacement de modèle, sinon votre personnalisation sera perdue lors de la prochaine mise à jour!

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

Cleaner Way:

Une méthode plus efficace et plus extensible consiste à ajouter un filtre personnalisé pour le transmettre. C'est quelques étapes supplémentaires, mais vous permet d'ajouter facilement une logique personnalisée supplémentaire si vous souhaitez remplacer la fonctionnalité au cas par cas en fonction de votre produit. 

Commencez par créer un filtre personnalisé avec un nom sémantiquement significatif et placez-le quelque part dans votre fichier functions.php pour le thème:

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

Ensuite, dans le fichier variable.php, au lieu d’appeler directement la fonction, transmettez-la à travers votre nouveau filtre:

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

La configuration de filtres personnalisés pour ce genre de choses prend un peu plus de temps, mais vous bénéficiez d'un avantage en termes de facilité de maintenance, car vous pouvez empiler ou désactiver des fonctions ultérieurement sans avoir à modifier davantage votre code existant.

Mise à jour pour WC 2.4

La version 2.4 de WooCommerce introduit une manière différente d’obtenir les attributs et leurs sélections associées. Comme ils n'ont toujours pas fourni de filtre pour cela, je vous recommande de remplacer la fonction wc_dropdown_variation_attribute_options à l'aide des méthodes décrites ci-dessus. Donc, copiez et collez toute la fonction dans le fichier functions.php de votre thème à partir de la déclaration, et ajoutez une variable pour le texte sélectionné si ce n'est pas une couleur ou une taille:

//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
10
Josh LaBau

Il existe en fait un moyen plus simple de le personnaliser.

Si vous examinez le fichier WC principal wc-template-functions.php, vous constaterez que le tableau situé à l'intérieur de la fonction wc_dropdown_variation_attribute_options est en fait ses arguments avec les paires de valeurs clé suivantes:

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

Maintenant, tout ce que vous avez à faire est de changer la même paire de valeurs de clé dans la fonction du fichier de modèle variable.php. Je voulais donc afficher l’étiquette déroulante au lieu du texte Choisir une option pour que je modifie le fu

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

Même chose avec d'autres paires. Hoep cela aide. En passant, cela ne fonctionne que dans WC 2.4+, alors soyez prudent.

6
Hooman Askari

J'ai trouvé un moyen avec WC 2.5. Ajoutez ceci à 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);
5
Marc

J'ai fait cela en utilisant une combinaison des autres réponses ici et cela a bien fonctionné pour moi. 

Cela a été fait avec WooCoommerce 3.3.5 et supposons que le filtre ait été ajouté relativement récemment. 

Vous utilisez le filtre pour la fonction 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 ); 

J'espère que ça aide quelqu'un. 

4
Joe

Voici une solution assez simple pour WC> 2.4 qui évite de réécrire les fonctions et d'encombrer votre functions.php ..

Ajoutez le fichier variable.php à votre thème ( http://docs.woothemes.com/document/template-structure/ ) et modifiez-le (à partir de la ligne 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;?>

pour ça:

<?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 );
} ?>

Ceci remplacera 'Choisissez une option' par 'Choisissez une taille', 'Choisissez une couleur' ​​etc. en fonction du nom de votre attribut.

2
tommm

Si vous souhaitez modifier le texte de la liste déroulante «Choisissez une option» dans Woocommerce, ajoutez ce qui suit au fichier functions.php de votre thème:

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; 
}
1
Sigma Wadbude

Si vous vous demandez comment remplacer «Choisissez une option» par le nom de l’attribut ou de la variante correspondant, voici comment procéder: ..__donnez variable.php et recherchez le code comme celui illustré ci-dessous.

Ouvrez le fichier variable.php (wp-content/plugins/woocommerce/includes/variable.php) dans votre woocommerce et modifiez-le (de la ligne 41 à 43): (Supprimez ce code de 3 lignes)

$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>' ) : '';

Puis ajoutez ce code

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

Cela fonctionne toute la version WordPress Merci

0
Savan Dholu