Выводим симпатичный значок корзины, который получает данные от модуля WooCommerce о количестве товаров в корзине и их цене. Эта реализация пригодится в том случае, если в шаблоне WordPress отсутствует значок корзины WooCommerce.
- Вставляем данный код в ту часть страницы, где хотите видеть значок корзины WooCommerce:
<!-- shopping cart --> <?php if (class_exists('woocommerce')) : ?> <div id="top-cart"> <div class="top-cart-icon"> <i class="fa fa-shopping-cart"></i> <a class="cart-items" href="/cart" title="Посмотреть корзину"> <div class="count"><?php echo sprintf(_n('%d товар', '%d товаров', WC()->cart->cart_contents_count, 'store'), WC()->cart->cart_contents_count); ?></div> <div class="total"> <?php echo WC()->cart->get_cart_total(); ?> </div> </a> </div> </div> <?php endif; ?> <!-- shopping cart end -->
- Вставляем стили в файл style.css
/* styles for shopping cart */ #top-cart { min-width: 100px; } #top-cart .cart-items { font-size: 12px; display: inline-block; } #top-cart i { transition: .4s all ease; -webkit-transition: .4s all ease; -moz-transition: .4s all ease; -ms-transition: .4s all ease; -o-transition: .4s all ease; font-size: 34px; } #top-cart:hover i { transform: translateX(5px); -webkit-transform: translateX(5px); -moz-transform: translateX(5px); -ms-transform: translateX(5px); -o-transform: translateX(5px); } .fa { display: inline-block; font: normal normal normal 14px/1 FontAwesome; font-size: inherit; text-rendering: auto; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } span.rur { font-family: rub-arial-regular; text-transform: uppercase; } span.rur span { display: none; } .fa-shopping-cart{ right: 5px; position: relative; } .fa-shopping-cart:before { content: "f07a"; }
- Подключаем иконочный шрифт в любое место между тегами <head> </head> Или подключаем иконочный шрифт font awesome любым удобным для вас способом.
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
Готово, при необходимости подредактируйте стили или разметку согласно вашему шаблону.
- Details
- Reviews
- Installation
- Development
WooCommerce Custom Add to Cart Button is a simple plugin to customize your store’s add to cart buttons. It makes it easy to change the ‘Add to cart’ button text, add a cart icon to the button, or replace the text with just an icon.
There are lots of reasons why you might want to change the add to cart text. Depending on how you’re using WooCommerce you might want the button to say something different like ‘Add to quote’, ‘Buy Now’, ‘BOOK EVENT’, ‘Enrol’ or ‘Make an Enquiry’.
You might want to make the button more visual by adding a cart icon before the text. Or you may want to replace the button text and just show a cart icon. The plugin uses the same cart icon that is built into WooCommerce itself.
Add to cart button options:
- Change the WooCommerce add to cart button text
- Add a cart icon next to the text
- Remove the text and just show a cart icon
- Case sensitive, so you get full control over whether the add to cart button text appears in uppercase, lowercase or sentence case
WooCommerce Custom Add to Cart Button is fully accessible. If you choose to display just the cart icon, the text is still present in the HTML and can be read by screen readers.
Options are set in the Customizer. Once installed, go to Appearance -> Customize -> WooCommerce -> Add to Cart Buttons and choose your settings.
WooCommerce Custom Add to Cart Button is fully compatible with other Barn2 plugins, including:
- WooCommerce Product Table – List products in a quick one-page order form.
- WooCommerce Quick View Pro – Speed up shopping by adding quick view lightboxes.
- WooCommerce Bulk Variations – Let customers buy multiple variations in a single click.
You can view the full plugin documentation in our Knowledge Base.
- Install via the Plugins screen in your WordPress dashboard, or download the ZIP, extract it, and upload to the
/wp-content/plugins/
directory. - Activate the plugin through the Plugins screen.
- Go to Appearance -> Customize, then go to WooCommerce -> Add to Cart Buttons to choose your settings.
- Change the Add To Cart button text and/or select the other options on this screen.
-
Will it work with my theme?
-
The plugin inherits the styles from your theme. This means that the button size, font and color will be the same as the existing add to cart buttons in your store. The plugin will change the text and add an icon without affecting the overall button styling.
-
Can I choose a different icon, change the size, change colors, etc?
-
We’ve kept the plugin deliberately simple and it’s not currently possible to make other changes such as different icons or changing colors. Please use the support tab or our feature request form if there’s anything else you’d like the plugin to do. We will add new features if there is enough demand.
-
Where can I find the documentation?
-
Please visit our Knowledge Base.
Plugin name is misleading. You can only customize the label text of the button or hide it. You can’t actually create a custom add to cart button and edit the button’s size, shape or color, you know like creating an actual «Custom» button. The icon that you can show is ugly, there should be an option to choose from different cart icons or add your own icon. Not bad for a free plugin but if you really need to create a «custom» add to cart button instead of just editing the label or hiding it, look somewhere else.
Resolved my issue , Thank you
Delighted to have found this. A simple enough thing to need to do but the code just a bit beyond my pay grade. So this seems to be a great answer. The developers website inspires confidence and I would return for other plugins if needed. So thanks Barn2!
Worked as per the description and seemed to be great, but I faced incompatibility issues and had to deactivate. I had problems with the permalinks and the language switcher.
Its great in my English website. Unfortunately I can’t find a feature how to set a different language when my website is multilanguage by WPML plugin. Also I miss a possibilities how to change a design of the button like color, size, change the picture etc. For that reason I cannot give 5 stars.
Plugin description is completely bullshit. This plugin can’t change add to cart button with icon/image..
Read all 7 reviews
“WooCommerce Custom Add To Cart Button” is open source software. The following people have contributed to this plugin.
Contributors
1.1.4
Release date 24 Nov 2022
- Tested up to WordPress 6.1.1 and WooCommerce 7.1
1.1.3
Release date 13 May 2022
- Tested up to WordPress 6.0 and WooCommerce 6.5.1
1.1.2
Release date 27 July 2021
- Tested up to WordPress 5.8 and WooCommerce 5.5.2
1.1.1
Release date 2 October 2020
- Tested up to WordPress 5.5.1 and WooCommerce 4.6.
- Minor code improvements.
- Added Composer support.
1.1
Release date 20 November 2019
- Update plugin architecture and Barn2 library code.
- Added link to settings page from main Plugins menu.
- Tested up to WordPress 5.3 and WooCommerce 3.8.
1.0
Release date 21 February 2018
- Initial release.
- Details
- Reviews
- Installation
- Development
WooCommerce Custom Add to Cart Button is a simple plugin to customize your store’s add to cart buttons. It makes it easy to change the ‘Add to cart’ button text, add a cart icon to the button, or replace the text with just an icon.
There are lots of reasons why you might want to change the add to cart text. Depending on how you’re using WooCommerce you might want the button to say something different like ‘Add to quote’, ‘Buy Now’, ‘BOOK EVENT’, ‘Enrol’ or ‘Make an Enquiry’.
You might want to make the button more visual by adding a cart icon before the text. Or you may want to replace the button text and just show a cart icon. The plugin uses the same cart icon that is built into WooCommerce itself.
Add to cart button options:
- Change the WooCommerce add to cart button text
- Add a cart icon next to the text
- Remove the text and just show a cart icon
- Case sensitive, so you get full control over whether the add to cart button text appears in uppercase, lowercase or sentence case
WooCommerce Custom Add to Cart Button is fully accessible. If you choose to display just the cart icon, the text is still present in the HTML and can be read by screen readers.
Options are set in the Customizer. Once installed, go to Appearance -> Customize -> WooCommerce -> Add to Cart Buttons and choose your settings.
WooCommerce Custom Add to Cart Button is fully compatible with other Barn2 plugins, including:
- WooCommerce Product Table – List products in a quick one-page order form.
- WooCommerce Quick View Pro – Speed up shopping by adding quick view lightboxes.
- WooCommerce Bulk Variations – Let customers buy multiple variations in a single click.
You can view the full plugin documentation in our Knowledge Base.
- Install via the Plugins screen in your WordPress dashboard, or download the ZIP, extract it, and upload to the
/wp-content/plugins/
directory. - Activate the plugin through the Plugins screen.
- Go to Appearance -> Customize, then go to WooCommerce -> Add to Cart Buttons to choose your settings.
- Change the Add To Cart button text and/or select the other options on this screen.
-
Will it work with my theme?
-
The plugin inherits the styles from your theme. This means that the button size, font and color will be the same as the existing add to cart buttons in your store. The plugin will change the text and add an icon without affecting the overall button styling.
-
Can I choose a different icon, change the size, change colors, etc?
-
We’ve kept the plugin deliberately simple and it’s not currently possible to make other changes such as different icons or changing colors. Please use the support tab or our feature request form if there’s anything else you’d like the plugin to do. We will add new features if there is enough demand.
-
Where can I find the documentation?
-
Please visit our Knowledge Base.
Plugin name is misleading. You can only customize the label text of the button or hide it. You can’t actually create a custom add to cart button and edit the button’s size, shape or color, you know like creating an actual «Custom» button. The icon that you can show is ugly, there should be an option to choose from different cart icons or add your own icon. Not bad for a free plugin but if you really need to create a «custom» add to cart button instead of just editing the label or hiding it, look somewhere else.
Resolved my issue , Thank you
Delighted to have found this. A simple enough thing to need to do but the code just a bit beyond my pay grade. So this seems to be a great answer. The developers website inspires confidence and I would return for other plugins if needed. So thanks Barn2!
Worked as per the description and seemed to be great, but I faced incompatibility issues and had to deactivate. I had problems with the permalinks and the language switcher.
Its great in my English website. Unfortunately I can’t find a feature how to set a different language when my website is multilanguage by WPML plugin. Also I miss a possibilities how to change a design of the button like color, size, change the picture etc. For that reason I cannot give 5 stars.
Plugin description is completely bullshit. This plugin can’t change add to cart button with icon/image..
Read all 7 reviews
“WooCommerce Custom Add To Cart Button” is open source software. The following people have contributed to this plugin.
Contributors
1.1.4
Release date 24 Nov 2022
- Tested up to WordPress 6.1.1 and WooCommerce 7.1
1.1.3
Release date 13 May 2022
- Tested up to WordPress 6.0 and WooCommerce 6.5.1
1.1.2
Release date 27 July 2021
- Tested up to WordPress 5.8 and WooCommerce 5.5.2
1.1.1
Release date 2 October 2020
- Tested up to WordPress 5.5.1 and WooCommerce 4.6.
- Minor code improvements.
- Added Composer support.
1.1
Release date 20 November 2019
- Update plugin architecture and Barn2 library code.
- Added link to settings page from main Plugins menu.
- Tested up to WordPress 5.3 and WooCommerce 3.8.
1.0
Release date 21 February 2018
- Initial release.
Задача. Необходимо в на сайте с Woocommerce заменить текст кнопки «В корзину» (Добавить в корзину, Просмотр корзины, Оформить заказ, Add to cart).
Решение. Для изменения текста или замены на иконку в кнопке заказа товара вставляем в functions.php
Код №1 или Код №2, если необходимо изменить кнопки только в некоторых товарах.
Изменение текста кнопки заказа
// Custom text Add to cart add_filter( ‘woocommerce_product_single_add_to_cart_text’, ‘woo_custom_cart_button_txt’ ); // add_filter( ‘woocommerce_product_add_to_cart_text’, ‘woo_custom_cart_button_txt’ ); function woo_custom_cart_button_txt() { return __( ‘Новая подпись кнопки В корзину’, ‘woocommerce’ ); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// Текст кнопки заказа товара по id товара function woo_unique_add_to_cart_text() { global $product; if( $product—>id == 11 ){ return __( ‘Купить сейчас’, ‘woocommerce’ ); // Для товара с id=11 } elseif($product—>id == 12){ return __( ‘Купить по лучшей цене’, ‘woocommerce’ ); // Для товара с id=12 } else{ return __( ‘В корзину’, ‘woocommerce’ ); // Для остальных } } add_filter( ‘woocommerce_product_single_add_to_cart_text’, ‘woo_unique_add_to_cart_text’, 10, 3 ); |
Также можно использовать плагин Customizer for WooCommerce — позволяет настраивать различные названия кнопок, вкладок и пр. в WC.
Замена текста кнопки заказа на иконку
Когда нужно было заменить текст кнопки заказа на иконку, то способы выше не подошли, т.к. они выводят иконку вида <i class="fa fa-shopping-cart"></i>
как текст, а не как html-код.
Решение 1. Для замены текста кнопки добавления в корзину на иконку:
- В файле плагина
woocommerce/templates/loop/add-to-cart.php
(этот файл нужно скопировать в папку с темой в такойже иерархии папок и потом его редактируем) - Заменить
esc_html( $product->add_to_cart_text() )
наsprintf('<i class="fa fa-shopping-cart"></i>')
.
Привет! Мы продолжаем разбирать самые интересные и полезные плагины для интернет-магазина woocommerce! Сегодня вы узнаете как добавить значок корзины и функцию корзины в меню своего сайта. В меню, рядом со значком корзины будет отображаться количество добавленных товаров в корзину и их общая стоимость. В настройках вы сможете выбрать расположение корзины в меню, слева, справа или по умолчанию. Можно будет выбрать определённое меню для показа корзины.
Установить плагин WooCommerce Menu Cart вы сможете прямо из админ-панели wordpress. Перейдите на страницу: Плагины — Добавить новый, введите название плагина в форму поиска, нажмите Enter, установите и активируйте плагин.
Далее, после установки и активации плагина, перейдите на страницу: Настройки — Menu Cart Setup. Здесь вы сможете настроить основные параметры плагина.
— Select which e-commerce plugin you would like Menu Cart to work with, если у вас установлено несколько плагинов электронной коммерции, то здесь можно выбрать в какой именно будет отображаться корзина.
— Select the menu(s) in which you want to display the Menu Cart, если у вас на сайте несколько меню, то здесь можно выбрать в каком меню будет отображаться корзина.
— Always display cart, even if it’s empty, поставьте здесь галочку, чтобы всегда отображать корзину в меню, даже если она пустая.
— Display shopping cart icon, показывать значок корзины, по умолчанию включено.
— Display cart contents in menu fly-out, показывать содержание корзины в выпадающем списке, доступно только в pro версии плагина.
— Set maximum number of products to display in fly-out, установить максимальное отображение товаров в выпадающем списке корзины. Доступно только в pro версии плагина.
— Choose a cart icon, можно выбрать значок корзины, только в pro версии плагина.
— What would you like to display in the menu, что отображать в корзине, по умолчанию отображаются и цены и товары.
— Select the alignment that looks best with your menu, можно выбрать расположение корзины в меню, слева, справа или по умолчанию.
— Enter a custom CSS class (optional), можно задать свои CSS стили для корзины.
— Use Built-in AJAX, можно включить Ajax поддержку для корзины, для более быстрой загрузки.
— Сохраните изменения.
Далее, после сохранения настроек, перейдите на сайт, в меню у вас появится значок корзины. При добавлении товаров в корзину, в меню будет отображаться количество товаров и их стоимость.
Остались вопросы? Напиши комментарий! Удачи!
Опубликовано: ADv
Дата 19.08.2014
в рубрике WooCommerce, Код за плагин
22 комментария
Недавно на одном из форумов сети меня спросили, существует ли хорошая инструкция о том, как добавить корзину в меню, отображающую количество товаров в ней и общую сумму с помощью WooCommerce. Можно конечно же использовать соответствующий плагин, однако есть решение и с помощью кода. В этой статье мы поделимся кодом, «извлеченным» из плагина Woocommerce Menu Cart, который можно поместить в файл functions.php вашей темы. Код выведет количество товаров в корзине и их общую стоимость в основном меню справа.
В том случае, когда товаров в корзине не окажется, меню будет выглядеть таким образом:
“0 товаров – $0? — эта ссылка будет вести на основную страницу магазина WooCommerce, обычно это http://example.com/shop/
Когда же в корзине будет хотя бы один товар, меню навигации будет выглядеть так:
Клик на “2 товара – $47? в этом примере переместит покупателя на страницу Корзины, http://example.com/cart/
Для реализации задуманного добавляем следующий код в файл functions.php вашей темы:
<?php //* Активируем поддержку шрифта Font Awesome add_action( 'wp_enqueue_scripts', 'enqueue_font_awesome' ); function enqueue_font_awesome() { wp_enqueue_style( 'font-awesome', '//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css' ); } /** * Помещаем иконку корзины с количеством товаров и общей стоимостью в меню навигации. * * Источник: http://wordpress.org/plugins/woocommerce-menu-bar-cart/ */ add_filter('wp_nav_menu_items','sk_wcmenucart', 10, 2); function sk_wcmenucart($menu, $args) { // Проверяем, установлен ли и активирован плагин WooCommerce и добавляем новый элемент в меню, назначенному основным меню навигации if ( !in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) || 'primary' !== $args->theme_location ) return $menu; ob_start(); global $woocommerce; $viewing_cart = __('View your shopping cart', 'your-theme-slug'); $start_shopping = __('Start shopping', 'your-theme-slug'); $cart_url = $woocommerce->cart->get_cart_url(); $shop_page_url = get_permalink( woocommerce_get_page_id( 'shop' ) ); $cart_contents_count = $woocommerce->cart->cart_contents_count; $cart_contents = sprintf(_n('%d item', '%d items', $cart_contents_count, 'your-theme-slug'), $cart_contents_count); $cart_total = $woocommerce->cart->get_cart_total(); // Раскомментируйте строку ниже для того, чтобы скрыть иконку корзины в меню, когда нет добавленных товаров в корзине. // if ( $cart_contents_count > 0 ) { if ($cart_contents_count == 0) { $menu_item = '<li class="right"><a class="wcmenucart-contents" href="'. $shop_page_url .'" title="'. $start_shopping .'">'; } else { $menu_item = '<li class="right"><a class="wcmenucart-contents" href="'. $cart_url .'" title="'. $viewing_cart .'">'; } $menu_item .= '<i class="fa fa-shopping-cart"></i> '; $menu_item .= $cart_contents.' - '. $cart_total; $menu_item .= '</a></li>'; // Раскомментируйте строку ниже для того, чтобы скрыть иконку корзины в меню, когда нет добавленных товаров в корзине. // } echo $menu_item; $social = ob_get_clean(); return $menu . $social; }
Если вы захотите добавить иконку корзины в произвольное меню, то поменяйте на нужное значение в строке 20.
Если вы хотите, чтобы иконка корзины в меню появлялась только тогда, когда в ней есть хотя бы один товар, тогда расскомментируйте строки 32 и 44
По всем вопросам и отзывам просьба писать в комментарии ниже.
Не забывайте, по возможности, оценивать понравившиеся записи количеством звездочек на ваше усмотрение.
Rating: 3.9/5 (60 votes cast)
Теги: functions.php woocommerce wordpress меню плагин
Об авторе ADv
Занимаюсь разработкой сайтов и магазинов на WordPress. Оказываю платные помощь и консультации.
Skype: advokat_b
3 ответа
Надеюсь, что следующий код поможет: Пожалуйста, проверьте скриншот
.site-header-cart .cart-toggler .cart-contents:after {
content: "";
font-family: FontAwesome;
margin-left: 14px;
}
.site-header-cart .cart-toggler .cart-contents .count {
line-height: 15px;
text-align: center;
font-size: 12px;
display: block;
width: 100%;
height: 100%;
font-weight: normal;
position: absolute;
Tristup
31 окт. 2018, в 14:03
Поделиться
-
0
Зачем использовать: после псевдо? а затем добавить дополнительную маржу?
Solomax
31 окт. 2018, в 14:27 -
0
@Solomax, использование до не будет достигать точного дизайна, показанного на скриншоте. Вы можете использовать мой код в Stylebot, чтобы понять. Любая проблема, дайте мне знать.
Tristup
01 нояб. 2018, в 04:43
Вы можете изменить значок корзины с помощью CSS с помощью кода ниже в CSS,
.site-header-cart .cart-toggler .cart-contents {
content: '';
background: url('URL_TO_YOUR_CART_IMAGE') no-repeat center center;
background-size: contain;
width: 20px;
height: 20px;
margin: -2px -4px;
display: inline-block;
}
Замените URL_TO_YOUR_CART_IMAGE URL-адресом значка вашей корзины.
Priyanka Modi
31 окт. 2018, в 12:37
Поделиться
Сделать это проще без использования изображений. Добавьте псевдокласс: перед вот так:
Удалить границу:
.site-header-cart .cart-toggler .cart-contents {border:0px;}
затем добавьте:
.site-header-cart .cart-toggler .cart-contents:before {
content: "f07a";
font-family: FontAwesome!important;
}
Добавьте это в свою дочернюю тему или перейдите в настройщик и добавьте его в раздел «Дополнительные CSS»
Solomax
31 окт. 2018, в 12:27
Поделиться
-
0
Круто, я попробовал последнее предложение, и оно сработало.
Может позже попробую поменять иконку.
Senja
31 окт. 2018, в 14:18 -
0
Приятно помочь, но вопрос не менялся?
Solomax
31 окт. 2018, в 14:30
Ещё вопросы
- 1OpenWeatherMap получит среднюю температуру за день
- 0База данных — Что такое хороший дизайн базы данных для системы бронирования?
- 1Как изменить операцию в Python с вводом? [Дубликат]
- 0Ошибка проверки PHP
- 0Есть ли способ вручную принудительно обновить ионный сбор-повтор?
- 0Таблицы не оформлены должным образом
- 0изображение не отображается даже после преобразования в base64
- 1NullReferenceException При вызове функции класса c # [duplicate]
- 0xslt concat текстовая строка до и после <newline /> [duplicate]
- 1Деструктуризация объекта параметра функции приводит к неопределенным переменным
- 0CSRF токены добавляются в запросы
- 1Не могу запустить Java в искровой рабочий
- 1Ролевая авторизация в asp.net
- 0Добавление нескольких кнопок в корзину с помощью php
- 1Поиск победителя в Tic-Tac-Toe (Java с использованием 2-D массивов)
- 1Извлечение свойств объекта JSON в новый массив с помощью Javascript
- 0Объединить MySQL Queries в таблицу
- 0Данные MySQL не отображаются в соответствии с идентификатором в таблице HTML
- 1Связывание действий внутри вкладки
- 0Получить QImage или QPixmap из QStandardItemModel — TableView
- 1Как скрыть свойство Items в пользовательском ComboBox
- 0Случайный маркер на картах Google Jquery
- 1Использовать макет как OverlayItem на MapView?
- 0JQuery Хорошая практика кодирования
- 1Firefox запускает событие нажатия одновременно с событием contextmenu
- 1Android SQLite запросы помечены как ошибка Android Studio
- 1Apache POI: Word получить размеры изображения
- 0Bootstrap 3: фиксированный столбец с отзывчивым столбцом
- 0Создать функции из значений массива
- 1Python запросы — Put игнорирует загрузку файлов
- 1Столбцы JTable не изменяют размер, вероятно, когда размер JFrame
- 1Есть ли необходимость в использовании обобщенных шаблонных шаблонов в методе сквозной передачи?
- 1Запрос Firebase удаляет все элементы
- 0Проблемы с глобальными сообщениями в Magento
- 0PayPal IPN Subscriber Amount Оплаченная переменная недоступна
- 0Эквивалент lseek для Linux в Windows API?
- 0Преобразование многомерного массива в XML с SimpleXML
- 1назначение пула соединений с базой данных?
- 1Настройки чтения с телефона на Android
- 1Spannable от Android
- 0Использование динамического сбоя памяти программы на C ++
- 0Ошибка Loopback 401 при попытке обновления
- 0Как получить параметры в URL после последнего появления определенного символа
- 1Получение текста из списка
- 1Создание кнопки разделения для пользовательского адаптера ListView
- 1Как использовать System.Windows.Controls.WebBrowser без его отображения?
- 1Поиск элементов в массиве с помощью бинарного поиска
- 0как сделать связанный список иметь дочерний узел
- 1Размер столбца TableLayout
- 1SQLAlchemy: динамически применять фильтр к столбцу отношений заранее