Замените кнопку «Добавить в корзину» в цикле кнопкой, связанной с продуктом, и другим текстом в зависимости от категорий

В WooCommerce я изменил кнопку «Добавить в корзину» на «Просмотр продукта» на странице магазина следующим образом:

// First, remove Add to Cart Button
add_action( 'after_setup_theme', 'my_remove_add_to_cart', 99 );
function my_remove_add_to_cart() {
    remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );    
}

// Second, add View Product Button
add_action( 'woocommerce_after_shop_loop_item', 'custom_view_product_button', 10 );
function custom_view_product_button() {
    global $product;
    $link = $product->get_permalink();
    echo '<a href = "' . $link . '" class = "button addtocartbutton">View product</a>';
}  

Но также мне нужен разный текст на кнопке «Просмотреть продукт» для разных категорий.

Мне нужно 5 разных текстов для 5 разных категорий только для кнопки «Просмотреть товар» на странице магазина (на странице одного товара должна оставаться кнопка «Добавить в корзину»).

Я использовал этот код для изменения кнопки «Просмотреть продукт», но не знаю, как отображать другой текст «Просмотреть продукт» для разных категорий продуктов.

Итак, как-нибудь добавьте к этому коду разный текст «Просмотр продукта» для 5 разных категорий на странице магазина.

Категория 1 -> Посмотреть текст продукта 1

Категория 2 -> Посмотреть текст продукта 2 и т. д.

🤔 А знаете ли вы, что...
PHP является интерпретируемым языком программирования.


1
64
1

Ответ:

Решено

Вместо того, чтобы удалять кнопку «Добавить в корзину» и заменять ее собственной кнопкой, вы можете использовать фильтр woocommerce_loop_add_to_cart_link.

Текст кнопки будет отличаться в зависимости от категорий товаров.

Поскольку вы его не используете, вы также можете отключить добавление Ajax в корзину (в настройках WooCommerce):

Теперь в первой функции ниже вы определите идентификатор (идентификаторы), имя (имена) или ярлык (имена) термина вашей категории продуктов, а также для каждой категории (категории) соответствующий текст, который будет отображаться на кнопке. Вы можете определить один или несколько терминов категории для каждого текста.

Код:

// Settings function: Define for each categories, the corresponding button text to display
function get_category_button_text() {
    return array(
        array(
            'terms' => array('hoodies', 'pants'), // Accept multiple categories term Ids, term slugs or term names
            'text' => __('Button Text 1', 'woocommerce') // Button text
        ),
        array(
            'terms' => array('tshirts', 'shirts'), 
            'text' => __('Button Text 2', 'woocommerce')
        ),
        array(
            'terms' => array('accessories'), 
            'text' => __('Button Text 3', 'woocommerce')
        ),
        array(
            'terms' => array('music', 'video'), 
            'text' => __('Button Text 4', 'woocommerce')
        ),
        array(
            'terms' => array('furniture'), 
            'text' => __('Button Text 5', 'woocommerce')
        ),
    );
}

// Replace Loop Add to Cart with a button linked to the product
add_filter( 'woocommerce_loop_add_to_cart_link', 'replacing_add_to_cart_button', 1000, 2 );
function replacing_add_to_cart_button( $button, $product  ) {
    $taxonomy    = 'product_cat';
    $product_id  = $product->get_id();
    $button_text = __('View product', 'woocommerce'); // The default text

    // Loop through defined category terms / text pairs
    foreach( get_category_button_text() as $values ) {
        if ( has_term($values['terms'], $taxonomy, $product_id ) ) {
            $button_text = $values['text'];
            break;
        } 
    }
    return sprintf('<a href = "%s" class = "button addtocartbutton">%s</a>', $product->get_permalink(), $button_text );
}

Код находится в файле function.php вашей дочерней темы (или в плагине). Протестировано и работает.


Альтернативный код:

Вы также можете использовать следующую альтернативу (похожую):

// Settings function: Define for each categories, the corresponding button text to display
function get_category_button_text() {
    return array(
        array(
            'terms' => array('hoodies', 'Hoodtwo', 'pants'), // Accept multiple categories term Ids, term slugs or term names
            'text' => __('Button Text 1', 'woocommerce') // Button text
        ),
        array(
            'terms' => array('tshirts', 'shirts'), 
            'text' => __('Button Text 2', 'woocommerce')
        ),
        array(
            'terms' => array('accessories'), 
            'text' => __('Button Text 3', 'woocommerce')
        ),
        array(
            'terms' => array('music', 'video'), 
            'text' => __('Button Text 4', 'woocommerce')
        ),
        array(
            'terms' => array('furniture'), 
            'text' => __('Button Text 5', 'woocommerce')
        ),
    );
}

// Replace Loop Add to Cart with a button linked to the product
add_action( 'after_setup_theme', 'replace_loop_add_to_cart_button', 999 );
function replace_loop_add_to_cart_button() {
    remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 ); 
    add_action( 'woocommerce_after_shop_loop_item', 'custom_loop_button_replacement', 10 );
}

// Custom button
function custom_loop_button_replacement() {
    global $product;

    $taxonomy    = 'product_cat';
    $product_id  = $product->get_id();
    $button_text = __('View product', 'woocommerce'); // The default text

    // Loop through defined category terms / text pairs
    foreach( get_category_button_text() as $values ) {
        if ( has_term($values['terms'], $taxonomy, $product_id ) ) {
            $button_text = $values['text'];
            break;
        } 
    }
    printf('<a href = "%s" class = "button addtocartbutton">%s</a>', $product->get_permalink(), $button_text );
}

Код находится в файле function.php вашей дочерней темы (или в плагине). Проверено и тоже работает.


Интересные вопросы для изучения