WordPress rest api

How does API work?

A programming interface (API) is a set of defined rules that describe how computers or applications communicate with each other. APIs act as a middleman that processes data transfers between an application and a web server.

Many APIs, such as the WooCommerce REST API, require the use of an API key. An API key is a randomly generated string of characters that an API provider issues to a developer in order to authorize access to their (provider’s) API. API keys are often sent with client requests in order for the server to recognize the client.

“df107aa6-0e03-45f5-910e-44580fe75707”

Going back to how API works, let me break it down into points.

  1. A client application makes an API call, also known as Request, to get information. The web application sends this request to the webserver using the API’s Uniform Resource ID (URI).
  2. When the API receives a valid request, it makes a call to the external program or webserver.
  3. The web server returns a Response to the API with the requested information.
  4. The API sends the data to the first application that requested it.

Example

Let’s jump to the examples again.

When we go to a restaurant, we check the menu first, right? After we select our items, we call the waiter. The waiter takes the order to the kitchen. When the food is ready, the kitchen then calls the waiter. Finally, the waiter brings the food to us.

In the above example, we are the client. We are sending a request by ordering food. Our waiter is the API. The waiter takes our order(request) and then tells the kitchen (Server) what we requested. The kitchen then responds by preparing our requested food and calls the waiter when ready. The waiter(API) finally then brings us our food.

If we want to include an API key example into this, then we can use the table number in the picture, which is” Table 06.”

When the waiter takes the order, he writes the table number on the waiter’s pad to let the kitchen know exactly which table is requesting this food. Remember this line? – API keys are sent with client requests in order for the server to recognize the client.

What REST APIs Are (And Why They Matter)

The WP REST API ships with WordPress core.

REST APIs provide interoperability between completely different online solutions. In other words, you can have a lot of data stored in a program such as WordPress, and interact with that same data in a totally separate application (such as native mobile or desktop).

You previously had to spend thousands of dollars developing custom APIs for edge-case scenarios. Now, a REST API is included in every up-to-date installation of WordPress, and developers can freely experiment with new applications of it every single day. Not only is this great news for the creative developer, but readily available REST APIs are a powerful asset for businesses too. Integrated niche-specific software, compatibility with legacy solutions, and even connectivity to wearables are no longer out of reach!

Here are a few simple and practical examples of how to integrate REST API solutions into existing platforms:

  1. Decouple your data from its WordPress interface and build native apps with React Native.
  2. Syndicate content from multiple sites. This is particularly effective if your businesses manage a big network.
  3. Use the REST API to speed up production times by automating data synchronization, as Wired did when they launched their new site.
  4. Build apps that enable users to manage their profiles and content, much like Calypso does for WordPress users.

Now you’ve gotten a taste of what is possible for your average, run of the mill WordPress site, imagine what is possible for your full-fledged e-commerce store. WooCommerce adds extensive custom additions to the WordPress API, giving you access to all of your e-commerce data on top of regular posts and pages.

What You Can Achieve Using the WooCommerce API (4 Examples)

It’s tempting to simply say, “Everything is possible” when it comes to the WooCommerce API. However, it’s worth looking at a few common tasks you may encounter, along with some specific use cases.

1. Create, Update, and Delete Products

Since your store’s products are the lifeblood of your business, the WooCommerce API dedicates plenty of options to ensuring that you can manage them all. You can work with collected within WooCommerce, although some endpoints are read-only. There are even separate APIs for single products, variations, attributes and their terms, taxonomies, shipping classes, and reviews.

2. Process Orders and Their Associated Notes

If products are the lifeblood of your store, orders are the rocket fuel. As such, the WooCommerce API offers plenty to help you administer to orders and notes. Practically every property found within WooCommerce can be accessed, along with related billing, shipping, and metadata properties.

We’d argue that the majority of uses for this endpoint will be to list orders in some way. Even a simple offers you immense power. For example, a list can be parsed for multiple mentions of the same product, tallied for those orders where a multi-basket contained a specific item, and much more.

Batch updating order notes is another helpful use for this aspect of the API. Taking a collection of Christmas orders, splitting them out based on the status of each one, and organizing the resultant JSON into a spreadsheet could help you deliver orders quicker and more efficiently.

3. Adjust Tax Rates and Classes

Taxes are a headache for many store owners, especially when you’re dealing with international orders. As there are many different ways to apply taxes at various rates, the WooCommerce API offers multiple options for working with this data. The endpoints are broken down into two variants:

  • Tax rates: This is where the actual percentage is recorded, along with some other identifying data.
  • Tax classes: These are broad ranges of taxes that rates are applied to.

For example, you might create a 20% tax rate that is applied to the ‘Standard Rate’ class. In fact, being able to batch update tax rates is a good use of the WooCommerce API. A more unique example would be a setup where a tax rate or class is created based on a specific customer attribute. This is ideal for situations when you need to ‘qualify’ a customer before registering them or sending them to the checkout process.

4. Set Shipping Zones, Locations, and Methods

If you’ve ever tried to work with shipping in WooCommerce, you’ll understand what a minefield it can be. If you get any element wrong, the customer is impacted directly in an area that’s ripe for poor feedback and reviews. Fortunately, the WooCommerce API can work with all of the endpoints associated to shipping, such as zones, locations, and methods.

When compared to other aspects of the API, there aren’t too many attributes to work with here. However, there are still plenty of options available to help you work with your store’s data. While you’ll often want to ‘set and forget’ shipping information (given its complexity and impact on user experience), there are still some practical applications.

For example, you’ll likely be mindful of current COVID-19 regulations on both a state- and country-wide basis. With this in mind, you may consider using a combination of endpoints to restrict shipping to certain locations on a temporary basis. In addition, you could notify users about any delays at the time of purchase. This could happen on the checkout screen, or through mass communication.

How to Get Started With the WooCommerce REST API (In 3 Steps)

In the next few steps, you’ll learn how to authenticate and access the REST API from the command line interface. The final language you use to interact with the REST API will (of course) depend on the application you’re building.

Step 1: Prepare Your WooCommerce Installation for the REST API

To access WooCommerce’s data, you first need to prove to WooCommerce that you have permission. This is called ‘authentication,’ and it uses specially generated API keys to authorize the user. They work in two steps:

  1. WooCommerce creates two secret random strings of characters, called the Consumer Key and Secret Key.
  2. You use them in your REST API calls, proving your identity.

Before getting started, you’ll need to get one of those key sets. First, navigate to your WordPress dashboard and enable the REST API options under WooCommerce > Settings > API. Make sure the Enable the REST API checkbox is selected, and save your changes:

Next, select Keys/Apps so you can generate a unique API key that will serve as the secret password when connecting to the REST API. Click the Create an API Key button, and follow the prompts to give yourself access to your data:

Click Generate API Key to complete the process. Save the resulting keys somewhere safe! You’ll need them to follow the rest of the steps.

Step 2: Use the WooCommerce REST API Documentation to Learn About Its Inner Workings

Every application using the REST API is unique and requires different calls. Rather than learning every single REST API endpoint, you can use the to find what you need in any given situation. This will also help you keep up as the API receives updates.

It’s important to read through the introduction to become familiar with the standards. Here are a few highlights to note:

  1. Check the Requirements section to make sure you have the correct versions of WooCommerce and WordPress.
  2. Get familiar with JSON and JSONP, the primary method of data transfer.
  3. Learn the error codes to debug issues faster.
  4. Use the provided for even easier integration.

Using the documentation, you can see how easy it is to get different information from your installation. Let’s try looking at  using the API. Enter the following into the command line interface to get a JSON formatted list of products:

curl https://example.com/wp-json/wc/v2/products/ -u your_consumer_key:your_consumer_secret

To create a new product, you’ll add the POST command with a few extra parameters about your new product:

curl -X POST https://example.com/wp-json/wc/v2/products \
    -u your_consumer_key:your_consumer_secret \
    -H "Content-Type: application/json" \
    -d '{
  "name": "My New Product",
  "type": "simple",
  "regular_price": "99.99",
  "description": "Example long description.",
  "short_description": "Short description.",
  "categories": ,
  "images": [
    {
      "src": "http://example.com/woocommerce/wp-content/uploads/sites/56/2017/06/rest-api-product.jpg",
      "position": 0
    },
    {
      "src": "http://example.com/woocommerce/wp-content/uploads/sites/56/2017/06/rest-api-product-2.jpg",
      "position": 1
    }
  ]
}'

Try setting up a demo WooCommerce site to practice with, and use the terminal to interact with it until you’re comfortable with the various commands. Try viewing, creating, and modifying your store’s , , and .

Once you understand how to pull and create data using the REST API with authentication, you can use the native programming language of your new application to do the same. To help you along, the documentation provides code examples for Node.js and PHP.

Step 3: Integrate the REST API Within Other Applications

The REST API also enables you to interact using platforms otherwise unrelated to WordPress and WooCommerce, which is a key part of its power and appeal. The exact steps you need to take will depend on the platform you’re building and the features you’d like to integrate. To give you some ideas, let’s tweak some of the examples we covered earlier and imagine they were made for WooCommerce instead of a regular WordPress site:

  1. Build a native mobile shopping app using React Native, customized to meet your users’ shopping habits.
  2. Syndicate products from multiple WooCommerce sites in one convenient catalog.
  3. Test a beta version of your shopping site while keeping the data synced, so you don’t lose sales information.
  4. Build web and desktop applications where users can easily manage their accounts and past orders.

These examples should be more than enough to help you brainstorm new creative solutions, and by now, you should have a clear idea of just what is possible with the REST API. Once you’ve chosen a new project idea or found a useful place to integrate WooCommerce into an existing external application, all that’s left is to plan the project and begin building.

Почему нужно отключить Rest API в WordPress?

Отключая рест апи, я выделил для себя 4 главных причины:

  1. Наличие брешей в безопасности. Пока вы не используете эти механизмы, время идет, а обновления для них выходят редко. Поэтому со временем взломщики найдут в них уязвимые точки (к примеру – authentication) и попадут в админку вашего же блога, нанеся ему вред.
  2. Создание пассивной нагрузки на хостинг. Несмотря на то, что сама функция не используется, она все равно продолжает действовать и постоянно нагружает арендованные мощности, при этом не давая в полной мере реализовывать весь потенциал других возможностей.
  3. Дыра для DDoS атак. Путем генерации множества задач для API (отклонить пустые просьбы от стороннего клиента), чтобы он выдал ошибку 404, сервер будет нагружаться все больше и больше, в итоге отключившись. Это спровоцирует остановку работы всех сайтов, стоящих на этой машине.
  4. Увеличение скорости загрузки страниц и избыток cookie. Создавая каждое внешнее подключение (с тегом <link>) в хеад, вы увеличиваете время открытия ресурса. За этим последуют как санкции поисковых систем, так и снижения трафика (не только органического) с повышением количества отказов.

Неграмотные специалисты.

Большое количество сайтов на WP породило большое количество задач, для которых владельцы сайтов ищут большое количество исполнителей. Теперь любой мало-мальски разбирающийся в PHP и WP вебмастер считает себя настоящим специалистом и гордо пишет в резюме «Создаю и администрирую сайты». А иногда бывает и так, что кто-то заказывает у такого «специалиста» сайт, а тот просто ставит WP, пару плагинов, меняет тему – и вуаля, сайт за 10 тысяч рублей (а то и дороже) готов. Не буду обсуждать этическую сторону вопроса, однако количество людей, которые не могут справиться с простейшими задачами, а то и вовсе ломают сайт, постоянно растет.

JSON REST API и WORDPRESS

Ладно, мы поняли, что штука эта — полезная. Но разве WordPress уже не использует эти API в своей структуре? Ну да, один есть, и это — WordPress API. Используется он для WordPress-плагинов, и работает только с внутренними процессами WordPress. Но если мы говорим о взаимодействии с программным обеспечением извне, то этот API – устарел и не очень дружественен к пользователю. Новый WP API гораздо более универсален, так как создан для того, чтоб, WordPress мог с легкостью взаимодействовать с другими веб-сайтами и сервисами в интернете. С помощью универсального API можно отображать и сохранять контент с других сайтов и приложений, не зависимо от того, используется ли там движок WordPress или нет. Все верно, данный API позволяет платформе WordPress стать системой управления контентом, подходящей для любого приложения, написанного на любом языке.

Плюс, тоже самое работает и в обратном порядке. Все, что есть на вашем WordPress-сайте, будет также доступно и на любом внешнем веб-сайте и сервисе, включая:

  • Записи;
  • Страницы;
  • Пользовательские типы записей;
  • Медиа;
  • Комментарии;
  • Таксономии;
  • Пользователи;
  • И многое другое

Это работает, потому что в основе всего лежит HTTP, который доступен везде. Протокол позволяет сайтам посылать, создавать, читать, обновлять или удалять запросы между двумя сторонами. В HTTP команды POST, GET, PUT, и DELETE являются эквивалентами. Кроме того, API понимает URLы, структура которых похожа на директории, а как мы знаем, похожие ссылки как раз использует WordPress и другие системы управления контентом.

Суммируя сказанное, моно сказать, что если вы захотите перенести все записи определенного пользователя с вашего сайта на другой ресурс, то вы можете просто воспользоваться директивой —

GET http://yoursite.com/users/username.

Тоже самое касается и обновления единичных записей, удаления пользователей, публикации страниц и многого другого. Если коротко, то API позволяет вам управлять административной областью WordPress, без необходимости ручной авторизации и использовать контент, не принадлежащий WordPress.

Здорово, но безопасно ли это? Хорошая новость заключается в том, что  WordPress REST API имеет встроенные меры безопасности. Волшебное слово здесь – это аутентификация. У интерфейса есть и куки-аутентификация, и OAuth-аутентификация. Таким образом,  куки-аутентификация работает для плагинов и тем, а OAuth используется для аутентификации мобильных и веб-клиентов, а также клиентов настольных компьютеров. Оба метода лимитируют сторонние действия на вашем сайте. Так как API созданы для того, чтоб платформы могли лимитировано обмениваться строго определенной информацией, то ваши данные в полной безопасности.

WooCommerce PUT request examples

Next, let us explore some examples of write requests.

To update the “regular_price”, here is a example PUT request:

Click Body > JSON and enter this query

To update product meta data, here is a example PUT request:

Pass the “key” as name of database field, and value as value.

Update price of product variant

example url: https://yourdomain.com/wp-json/wc/v3/products/833/variations/854

To update a product or product variant’s “price” or “regular_price”, here is a example PUT request:

Click Body > JSON and enter this query

Pass the “key” as name of database field, and “value” as value.

Update customer’s first and last name

example url: https://yourdomain.com/wp-json/wc/v3/customers/3144/

  • Replace https://yourdomain.com with your domain
  • Replace 3144 with a specific customer ID in your store.
  • Find customer ID by clicking “edit” on the specific customer in WooCommerce and looking for the value after user_id=XXXX. In the example below, the customer ID is 3144

To update the “first_name” and “last_name”, here is a example PUT request:

Click Body > JSON and enter this query

To update a customer’s shipping address, here is a example PUT request:

Click Body > JSON and enter this query

Update line item meta data in a Order

Use this example to update line item meta in a specific Order. I would recommend doing a GET request and viewing the order meta data.

Introducing the WooCommerce REST API

The WooCommerce API lets you implement custom functionality for your site at a software level. You can code in a way that’s specifically designed to integrate with WooCommerce. As such, you can create practically any feature or functionality if you have the time, skill, and (potentially) budget.

In order to understand how this key feature works, you’ll want to become familiar with two terms:

  • Representational State Transfer (REST). This is a complicated topic, but for the purposes of this article, REST is a type of ‘web service’ that lets you access specific elements of a web page.
  • Application Programming Interface (API). In contrast to a Graphical User Interface (GUI), this is essentially a set of code hooks and filters that let you work with access points. Generally, you’ll code them into certain WordPress-based files.

In other words, REST defines what you can access on your site through code, and the API gives you the tools to leverage that access. Together, they enable you to make significant changes to how your site works.

Компоненты React и State

Компоненты — это строительные блоки React. Каждый компонент может иметь

  1. Props.
  2. Собственный State
  3. Методы, которые либо отображают что-то (например, render()), либо обрабатывают некоторую бизнес-логику

Создадим компонент, который будет получать все доступные сообщения и отображать их обратно пользователю. Чтобы сделать это, сначала напишем конструктор для класса и инициализируем state в конструкторе:

State является объектом JSON. Внутри конструктора мы объявили свойства title, date и content свойства содержимого внутри конструктора. tile и content являются объектами, а date — массивом.

Оптимизация и продвижение

Для оптимизации сайта на WordPress обычно используется плагин All In One SEO Pack. При установке расширения для электронной коммерции к нему необходимо добавить модуль, который размещает стандартный блок для SEO-оптимизации на страничке каждого товара и позволяет редактировать мета-теги. Рекомендуется заполнять только заголовок (title) и описание (description). All In One SEO Pack нужен также для настройки метаданных, которые будут определять внешний вид ссылок на сайт при размещении их на страницах в соцсетях.

Следующий шаг — настройка ЧПУ. Правильное отображение адресов обычно настраивается при первом запуске WordPress. Но в случае с использованием плагина WooCommerce в URL добавляется префикс product. Это не проблема с точки зрения оптимизации, страдает разве что чувство прекрасного. Убрать префикс можно двумя способами: через платный плагин или с помощью бесплатного расширения Permalink Manager Lite, которое требует настройки и ручной правки добавленных ранее товаров.

Для оптимизации магазина нужно создать ускоренные версии основных страниц и товарных карточек. Для этого используется плагин AMP для WooCommerce. Совсем без плагинов обойтись не удастся, потому что в базовой комплектации движка и плагина для электронной коммерции практически нет инструментов оптимизации и продвижения сайта.

Создание учетных данных Woocommerce REST API

В рамках этого руководства мы предположим, что у нас есть рабочий экземпляр WordPress с уже установленным плагином Woocommerce. Первое, что нам нужно сделать, это сгенерировать наши учетные данные Woocommerce REST API: они будутиспользуется в каждом HTTP-запросе, который мы будем выполнять. Создать учетные данные очень просто; все, что нам нужно сделать, это перейти к в вертикальном меню на странице администрирования WordPress:

Оказавшись на странице настроек плагина, мы нажимаем на вкладку «Дополнительно», а затем нассылку «REST API», которая находится под меню вкладок. На странице, которая будетчтобы открыть, нажимаем на кнопку «Создать ключ API»:

Нам будет представлена ​​форма создания ключа API, и нам будет предложено вставить:

  • Описание, которое будет использоваться как понятное имя, чтобы легко идентифицировать учетные данные.
  • Пользователь, который будет использовать ключ
  • Разрешения, которые будут предоставлены ключу (только чтение | только запись | чтение и запись)

Обратите внимание, что у нас есть возможность создать несколько ключей с разными разрешениями, чтобы ограничить операции, предоставляемые конкретному пользователю. Для этого урока мы создадим ключ API с разрешениями на чтение и запись:

Когда все будет готово, мы нажимаем кнопку «Создать ключ API», и оба потребительский ключ и секрет потребителя будут сгенерированы и показаны нам. Мы должны хранить и то, и другое в надежном месте, поскольку как только мы покинем страницу, они будут скрыты:

После того, как наши ключи сгенерированы, нам нужно выполнить еще одно действие из бэкэнда администрирования WordPress: мы должны убедиться, что правильный красивая постоянная ссылка используются, иначе конечные точки API не будут работать. Для выполнения задачи переходим к в левом вертикальном меню WordPress. В меню страницы выбираем «Название публикации», а затем сохраняем изменения:

Это все, что нам нужно сделать на стороне WordPress. В следующем разделе мы увидим, как взаимодействовать с REST API Woocommerce с помощью Python.

WooCommerce REST API

WordPress is by far the most popular content management system (CMS) now. No wonder they offer multiple APIs. WordPress REST API allows an application to interact with WordPress’s functionalities. WooCommerce API is an extension of the WordPress APIs, which allows third-party applications to create, update and delete WooCommerce data.

In simple words, WooCommerce REST API is an interface that lets you or your developers access your WooCommerce store without logging into your WordPress admin panel. Moreover, it allows you to enhance the functionality of your eCommerce store.

The WooCommerce Rest API was created to make it simple for your WordPress-based WooCommerce store to communicate with other online services and applications. This functionality is managed effectively via HTTP requests, which are universally accessible.

With the help of the HTTP protocol, WooCommerce WordPress websites are able to send service requests to and from endpoints. Service requests include create, read, update and delete (CRUD). Furthermore, The WooCommerce Rest API is perfectly capable of handling directory-like URL structures.

Conclusion

WooCommerce is a popular solution for ecommerce, in part because it offers a complete REST API to help you develop powerful solutions. Learning how to use it will help you build more robust and full-featured external apps for your clients.

In this article, we’ve introduced you to the power of the WooCommerce REST API, and helped familiarize you with three important things:

  1. Preparing a WooCommerce installation for REST API authorization.
  2. Reading and learning from the developer documentation.
  3. Integrating the REST API into external applications.

What questions do you have about developing with the WooCommerce REST API? Ask your questions in the comments section below!

Image Credit: Clark Young.

WordPress входит в новую эру

WordPress не только станут доступны новые типы контента, но благодаря новому API и контент WordPress станет доступен всему интернету. Системы, построенные не на основе  PHP, смогут использовать данные WordPress, адаптируя их с помощью собственных приложений.

Но интереснее всего звучит возможность использования WordPress-продуктов, к примеру, плагинов, на других платформах, и системах управления контентом.

Мобильные приложения, созданные на базе WordPress, будут доступны повсеместно, что является прекрасной новостью для всех тех, кто их создает или использует. Я думаю, что появятся решения, которые позволят обычному пользователю автоматически создавать мобильные приложения на базе WordPress-сайтов.

В итоге:

Nick Schäferhoff

Как вы сами видите, новый WordPress REST API трансформирует WordPress в нечто новое. Он откроет WordPress всему интернету, и позволит платформе органичнее взаимодействовать со сторонними приложениями и сервисами. Появление WordPress REST API порадует не только разработчиков, но и обычных пользователей, которые получат множество новых возможностей.

Автор оригинала Nick Schäferhoff

Конструктор мобильного клиента Simple WMS Client: способ создать полноценный ТСД без мобильной разработки. Теперь новая версия — Simple UI (обновлено 14.11.2019)

Simple WMS Client – это визуальный конструктор мобильного клиента для терминала сбора данных(ТСД) или обычного телефона на Android. Приложение работает в онлайн режиме через интернет или WI-FI, постоянно общаясь с базой посредством http-запросов (вариант для 1С-клиента общается с 1С напрямую как обычный клиент). Можно создавать любые конфигурации мобильного клиента с помощью конструктора и обработчиков на языке 1С (НЕ мобильная платформа). Вся логика приложения и интеграции содержится в обработчиках на стороне 1С. Это очень простой способ создать и развернуть клиентскую часть для WMS системы или для любой другой конфигурации 1С (УТ, УПП, ERP, самописной) с минимумом программирования. Например, можно добавить в учетную систему адресное хранение, учет оборудования и любые другие задачи. Приложение умеет работать не только со штрих-кодами, но и с распознаванием голоса от Google. Это бесплатная и открытая система, не требующая обучения, с возможностью быстро получить результат.

5 стартмани

09.01.2019   
75347   
286   

informa1555   

246
   

206

Действие WooCommerce и фильтр крюк

WooCommerce использует многоДействие и фильтр крюкДля того, чтобы запустить свой код, а не, например, кодирование функции в файле шаблона.

Это дает большую гибкость и означает, что вы можете настроить вывод WooCommerce без необходимости создавать дубликат файла шаблона.

Предположим, что вы хотите изменить код вывода на одной странице. Это содержит/ templatesПапкаcontent-single-product.phpДокумент.

Большая часть кода в этом файле шаблона состоит из крюков и сопровождается функциями. Этот файл содержит текст, комментарии, можно точно сказать, какие функции связаны.

Это пример:монтировать. В файле шаблон, у вас есть конец текста, список особенность, связанная с этим крюком, а затем использоватьСпусковой крючок сам.

Затем, если вы хотите изменить или отменить их, вам нужно будет найти функции, связанные с крючком действия. вы можетеВ документации WooCommerceповерниэти функцииизПолный список 。

Вы можете/ includesКод для этих функций в серии файлов в папке. Эти функции, как правило, логически именованные файлы. Поэтому, например, в примере выше кодФункция крюкcontent-single-product.phpФайл в файлеНа крюке,wc-template-functions.phpВ файле, файл содержит функцию, которая непосредственно присоединенную к функции. Крюк в файле шаблона.

Как вы можете видеть, освоить WooCommerce API, возможно, потребуется изучить структуру файла, но как только вы знакомы с ним, вы обнаружите, что эта структура является очень разумной, и в большинстве случаев, это легко выяснить местоположение кусок кода. Если вы не можете найти его, просто искать его в WooCommerce документе, он расскажет вам, где найти его.

ВышеупомянутыйФункцияВставная Это означает, что вы можете переписать его в свой собственный плагин или тему.

Просто напишите другую функцию с таким же именем. Когда WordPress встречает подключаемую функцию в WooCommerce, она проверяет, есть еще одна функция с тем же именем, и потому, что она существует, она не запускается версии WooCommerce этой функции: а запустить функцию. Обязательно, чтобы обеспечить полное идентичное имя.

Рейтинг
( Пока оценок нет )
Editor
Editor/ автор статьи

Давно интересуюсь темой. Мне нравится писать о том, в чём разбираюсь.

Понравилась статья? Поделиться с друзьями:
Бизнес стратегия
Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: