API плагин. API плагин Подключение стороннего api плагина майнкрафт

Plugins are a key piece of the webpack ecosystem and provide the community with a powerful way to tap into webpack"s compilation process. A plugin is able to hook into key events that are fired throughout each compilation. Every step of the way, the plugin will have full access to the compiler and, when applicable, the current compilation .

For a high-level introduction to writing plugins, start with writing a plugin .

Let"s start by going over tapable utility, which provides the backbone of webpack"s plugin interface.

Tapable

This small library is a core utility in webpack but can also be used elsewhere to provide a similar plugin interface. Many objects in webpack extend the Tapable class. The class exposes tap , tapAsync , and tapPromise methods which plugins can use to inject custom build steps that will be fired throughout a compilation.

It is possible to customize the printed output by passing different arguments to the reportProgress function of ProgressPlugin .

To report progress, a plugin must tap into a hook using the context: true option:

Compiler. hooks. emit. tapAsync ({ name: "MyPlugin" , context: true } , (context, compiler, callback) => { const reportProgress = context && context. reportProgress; if (reportProgress) reportProgress (0.95 , "Starting work" ) ; setTimeout (() => { if (reportProgress) reportProgress (0.95 , "Done work" ) ; callback () ; } , 1000 ) ; } ) ;

The reportProgress function may be called with these arguments:

reportProgress (percentage, ... args) ;
  • percentage: This argument is unused; instead, ProgressPlugin will calculate a percentage based on the current hook.
  • ...args: Any number of strings, which will be passed to the ProgressPlugin handler to be reported to the user.

Note that only a subset of compiler and compilation hooks support the reportProgress function. See ProgressPlugin for a full list.

Logging

Logging API is available since the release of webpack 4.37. When logging is enabled in stats configuration and/or when infrastructure logging is enabled, plugins may log messages which will be printed out in the respective logger format (stats, infrastructure).

  • Plugins should prefer to use compilation.getLogger("PluginName") for logging. This kind of logging is stored in the Stats and formatted accordingly. It can be filtered and exported by the user.
  • Plugins may use the compiler.getInfrastructureLogger("PluginName") for logging. Using infrastructure logging is not stored in the Stats and therefore not formatted. It"s usually logged to the console/dashboard/GUI directly. It can be filtered by the user.
  • Plugins may use special fallback logic for detecting logging support compilation.getLogger ? compilation.getLogger("PluginName") : console to provide a fallback for cases when an older webpack version is used which does not support getLogger method on compilation object.

Next Steps

See the compiler hooks section for a detailed listing of all the available compiler hooks and the parameters they make available.

Плагин представляет собой динамически загружаемую библиотеку (DLL). После установки программы все плагины, входящие в дистрибутив, помещаются в каталог c:\Program Files (x86)\Common Files\Soft Gold\Inventory 14\Plugins\... Расширение *.abl необходимо для автоматической загрузки плагина из указанного каталога при запуске приложения. Плагин также можно загрузить из любого другого места на диске, указав в настройках путь поиска.

Инициализация API плагина

{ Delphi VCL Extensions }

{ Plugin interface for ABViewer/Inventory }

{ Copyright (c) 2002-2010 SoftGold software company }

{************************************************************}

unit sgPluginItem;

interface

implementation

XMLDocRef: IXMLDocument = nil;

ClientRef: IXMLNode = nil;

P: Pointer = nil;

PluginsHostWnd: HWND = 0;

PluginsHostWndName: string = "";

XMLAtomString: string = "";

procedure InitializeDoc;

begin

// получение уникального имени класса окна с параметрами

PluginsHostWndName:= Format("TsgPluginsHost:%.8X:%.8X", );

// нахождение непосредственно окна

PluginsHostWnd:= FindWindow(PChar(PluginsHostWndName), nil);

If PluginsHostWnd <> 0 then

Begin

// получение строки атома для получения параметра xml документа

XMLAtomString:= Format("XMLOfs%.8X%.8X",

XMLDocRef:= IXMLDocument(GetProp(PluginsHostWnd, PChar(XMLAtomString)));

If Assigned(XMLDocRef) then

Begin

// добавление элемента в список

ClientRef:= XMLDocRef.DocumentElement.ChildNodes.ChildNodes.AddChild(sClient);

// инициализация адреса функции Invoke

ClientRef.ChildValues["Invoke"] := IntToId(Integer(@Invoke)); // шестнадцатиричное $XXXXXXXX

End;

End;

end;

initialization

CoInitialize(P);

InitializeDoc;

Настройка и запуск демонстрационной версии плагина

Демонстрационная версия плагина настраивается автоматически при установке программы и подключается сразу после запуска Inventory. В состав пакета входит исходный текст компонента (имя проекта sgPlugin.dpk) и демонстрационная версия плагина (имя проекта plug1.dpr ).

Порядок запуска плагина из режима отладки:

▪ Открыть C:\Users\USER_NAME\Documents\Inventory 14\Plugins\Source\Delphi\Demos\Plug1\plug1.dpr

▪ Установить в опциях проекта:

Search Path : «..\..\Components\PlugItem»;

Output derectory , например: «c:\Program Files\Common Files\Soft Gold\Inventory 14\Plugins»;

Host application , на вновь установленное приложение, например: «c:\Program Files\Soft Gold\Inventory 14\Inventory 14.exe».

▪ Запустить на выполнение.

Для использования компонента в designtime необходимо открыть, перебилдить и инсталировать C:\Users\USER_NAME\Documents\Inventory 14\Plugins\Source\Delphi\Components\PlugItem\sgPlugin.dpk . После инсталяции компонента, в палитре компонентов Delphi, на закладке Soft Gold появится компонент TsgPluginItem, который можно использовать в designtime, т.е. помещать на форму.

Hooks are provided by WordPress to allow your plugin to "hook into" the rest of WordPress; that is, to call functions in your plugin at specific times, and thereby set your plugin in motion. There are two kinds of hooks:

  1. (Codex )
  2. (Codex )

You can sometimes accomplish the same goal with either an action or a filter. For example, if you want your plugin to change the text of a post, you might add an action function to publish_post (so the post is modified as it is saved to the database), or a filter function to the_content (so the post is modified as it is displayed in the browser screen).

For a thorough listing of all action and filter hooks in WP see Adam Brown"s WordPress Hooks Database .

Function Reference

Filter Functions
Actions Functions
Activation/Deactivation/Uninstall Functions

Actions

Actions are triggered by specific events that take place in WordPress, such as publishing a post, changing themes, or displaying an . An Action is a custom PHP function defined in your plugin (or theme) and hooked , i.e. set to respond, to some of these events. Actions usually do one or more of the following:

  • Modify database data.
  • Send an email message.
  • Modify the generated administration screen or front-end page sent to a user browser.

The basic steps to make this happen (described in more detail below) are:

  1. Create a PHP function that should execute when a specific WordPress event occurs, in your plugin file.
  2. Hook this function to the event by using the function.
  3. Put your PHP function in a plugin file, and activate it.

Create an Action Function

The first step in creating an action in your plugin is to create a PHP function with the action functionality of your plugin and put it in your plugin file (your plugin file must go into the wp-content/plugins directory). For example, if you want your friends to get an email message whenever you create a new post, you might define the following function:

Function email_friends($post_ID) { $friends = "[email protected],[email protected]"; mail($friends, "sally"s blog updated", "I just put something on my blog: http://blog.example.com"); return $post_ID; }

For most actions, your function should accept a single parameter (usually the post or comment ID, depending on the action). Some actions take more than one parameter -- check the documentation for the action (if available) or the WordPress source code for more information. Besides the one parameter, you can also access the , and call other WordPress functions (or functions in your plugin file).

Any text output by the function (e.g. with print) will appear in the page source at the location where the action was invoked.

NOTE : Keep in mind that other plugins or the WordPress core may already be using the function name you have thought of. See the next section, for more information.

Avoiding Function Name Collisions

It is possible that someone has created a plugin with a function named the same as one in your plugin.

This is a problem because PHP does not allow multiple functions with the same name. If two plugins provide a function with the same name, or a plugin provides a function with a name the same as a WordPress function, the blog could cease to function. There are two ways to avoid this problem.

The first solution is to prefix every function in your plugin with a unique set of characters. If your name is John Q. Public, you might declare your functions as function jqp_output() {...} . The likelihood that someone with the same initials does the same thing with their plugin is possible but low.

The second - and possibly easier - a solution is to enclose your plugin functions in a class and call the class methods statically. This sounds more complicated than it is.

Consider this class, which expands on the examples provided above:

Class emailer { static function send($post_ID) { $friends = "[email protected],[email protected]"; mail($friends,"sally"s blog updated","I just put something on my blog: http://blog.example.com"); return $post_ID; } } add_action("publish_post", array("emailer", "send"));

This class called emailer has a method send that implements the plugin functionality.

The add_action() function outside of the class adds the action to WordPress that tells it to call the send method when a post is published. The array used in the second parameter tells the plugin system to call the static method of the class "emailer" named "send".

The function send is protected from the global namespace by the class declaration. It is not possible to call send() directly, and so any other function named send will not collide with this one. If you did want to call send(), you would need to use a scope resolution operator, like this: emailer::send()

The above example is for static methods. If you have an instance of a class then that won"t work. To call a method of an instance you need to pass the instance as a variable. Consider the above example modified to take this into account:

Class emailer { function send($post_ID) { $friends = "[email protected],[email protected]"; mail($friends,"sally"s blog updated","I just put something on my blog: http://blog.example.com"); return $post_ID; } } $myEmailClass = new emailer(); add_action("publish_post", array($myEmailClass, "send"));

Classes are a complicated subject. Read more about them in the PHP documentation on classes .

Hook to WordPress

After your function is defined, the next step is to "hook" or register it with WordPress. To do this, call in the global execution space of your plugin file:

Add_action ("hook_name", "your_function_name", , );

Hook_name The name of an action hook provided by WordPress, that tells what event your function should be associated with. your_function_name The name of the function that you want to be executed following the event specified by hook_name . This can be a standard php function, a function present in the WordPress core, or a function defined by you in the plugin file (such as "email_friends" defined above). priority An optional integer argument used to specify the order in which the functions associated with a particular action are executed (default: 10). Lower numbers correspond with earlier execution, and functions with the same priority are executed in the order added to the action. accepted_args An optional integer argument defining how many arguments your function can accept (default 1), useful because some hooks can pass more than one argument to your function. This parameter is new in release 1.5.1.

In the example above, we would put the following line in the plugin file:

Add_action ("publish_post", "email_friends");

Install and Activate

The last step in getting your filter hook to work is to install the file and activate the plugin. The PHP function you wrote and the call must go into a PHP file together, and the PHP file must be installed in the wp-content/plugins directory. Once it is installed, you will need to visit the admin section of WordPress and activate your plugin; see for more details.

Current Hooks for Filters

Activation/Deactivation/Uninstall

If your plugin has tasks to complete only at activation or deactivation time, it can use and Action Reference - A listing of WordPress"s action hooks

External Resources

  • Adam Brown"s WordPress Hooks Database , a database of all WordPress" hooks, showing which version they come from, and linking to the source code spots that use them. This is the most complete.
  • Otto on WordPress:

By Yandex.
It"s a web service, so you don"t need to add that.

Server owners need a special key to enable this plugin.
Login to the Yandex website and then obtain this key , then put it in the API"s config.
Please note that the free key supports "only" 10,000,000 characters every month, but you can create how many keys you want.

These are the avaible languages:

SpoilerTarget">Spoiler

AZERBAIJAN
ALBANIAN
ENGLISH
ARABIC
AFRIKAANS
BASQUE
BELARUSIAN
BULGARIAN
BOSNIAN
WELSH
HUNGARIAN
VIETNAMESE
HAITIAN
GALICIAN
DUTCH
GREEK
GEORGIAN
DANISH
INDONESIAN
IRISH
ITALIAN
ICELANDIC
SPANISH
KANNADA
CHINESE
KOREAN
LATIN
LITHUANIAN
MACEDONIAN
MONGOLIAN
GERMAN
NEPALI
NORWEGIAN
PERSIAN
POLISH
PORTUGUESE
ROMANIAN
RUSSIAN
SERBIAN
SLOVAKIAN
SLOVENIAN
SUNDANESE
TURKISH
UZBEK
UKRAINIAN
FINNISH
FRENCH
HINDI
CROATIAN
CZECH
SWEDISH
SCOTTISH
ESTONIAN
JAPANESE

When you join the server, your language is the server language.
To change it, just type /lang (permission: translator.lang ) and select your language from the menu.

If you don"t know how to add dependencies, read here.

Developer
Be sure you are using Java >= 8.
Add the JAR to your build path. Then set the "Manual Manifest" setting and create your MANIFEST.MF to the project. Write:

Main-Class: your.package.Class
Class-Path: ..\lib\Translator.jar

Server owners
Be sure you are using Java >= 8.
Create a folder named lib in the main server root, and put here the JAR.
Also, you need to put it in your plugins folder.

//Sending a message translated automatically to the player language
p.sendMessage("§a" + Translator.translate("Hello!", p));

//Sending a message translated manually
p.sendMessage("§a" + Translator.translate("Hello!", Language.ENGLISH, Language.ITALIAN));

//Getting the server language
Language serverLang = Translator.getServerLanguge();

//Getting player"s language
Language playerLang = Translator.getPlayerLanguage(p);

  • If you reload the API while a plugin that uses it is enabled, it will crash. To fix manually, unload the plugin, reload the API and load the plugin
  • Color codes are not supported. To use them see the examples above
  • Little lag (the API needs to translate the original text and receive JSON)

If you have any problem, write a post in the discussion or contact me via private messages. I will not reply to bug reports on the reviews section.

Currently there are not plugins that are using this API. If you are using it, tell me it and I will add it here

Recent Reviews

  1. Version: 1.0

    Grande frate! Ho letto Powered by Gamehosting, quindi penso tu sia italiano? se si: sai perché da questo errore all" avvio?

    P.s (ho letto impossibile trovare il percorso specificato, ma la cartella ci sta)

    : java.io.IOException: Impossibile trovare il percorso specificato
    : at java.io.WinNTFileSystem.createFileExclusively(Native Method)
    : at java.io.File.createNewFile(Unknown Source)
    : at eu.iamgio.translator.UsersFileLoader.loadRegisterFile(UsersFileLoader.java:21)
    : at eu.iamgio.translator.Translator.onEnable(Translator.java:35)
    : at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:321)
    : at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:340)
    : at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:405)
    : at org.bukkit.craftbukkit.v1_8_R3.CraftServer.loadPlugin(CraftServer.java:357)
    : at org.bukkit.craftbukkit.v1_8_R3.CraftServer.enablePlugins(CraftServer.java:317)
    : at net.minecraft.server.v1_8_R3.MinecraftServer.s(MinecraftServer.java:414)
    : at net.minecraft.server.v1_8_R3.MinecraftServer.k(MinecraftServer.java:378)
    : at net.minecraft.server.v1_8_R3.MinecraftServer.a(MinecraftServer.java:333)
    : at net.minecraft.server.v1_8_R3.DedicatedServer.init(DedicatedServer.java:263)
    : at net.minecraft.server.v1_8_R3.MinecraftServer.run(MinecraftServer.java:525)
    : at java.lang.Thread.run(Unknown Source)

Вышедшему в конце 2015. Однако, по большому счёту, только продвинутые разработчики нашли время, чтобы узнать, насколько мощным является это предложение.

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

В этой статье, мы представим вам проект WordPress REST API, разъясним, чем он так хорош, потом предложим несколько идей его использования. Поэтому не теряем время и начинаем!

Знакомство с WordPress REST API

Проект WordPress REST API (REST от англ. Representational State Transfer – «передача состояния через представления») подтверждает, что WordPress делает шаги к тому, чтобы стать полноценной платформой приложений. Его наличие – это неоспоримое доказательство, поскольку оно добавляет стандартный REST API к ядру WordPress.

Проект вначале был загружен на GitHub для разработчиков в 2013 разработчиками Ryan McCue и Rachel Baker . Независимый плагин REST API был встроен в ядро WordPress в декабре 2015 , после того, как получил огромную поддержку и привлёк около 100 участников, желающих работать над улучшением его возможностей.

С момента, когда WordPress API REST стал частью ядра, он доказал свою эффективность. Вот лишь несколько реальных примеров для наглядности применения и вдохновения в своих проектах:

  1. Event Espresso применяет REST API для обеспечения доступа разработчикам к их международной инфраструктуре, позволяя разрабатывать приложения, с применением их сервисов.
  2. Simmer разрешает разработчикам доступ к API в целью расширения своей функциональности в полноценное мобильное приложение или настраивания тем.
  3. JoinIn предоставляет собственный виджет «встраиваемый» с использованием REST API, заполняя его соответствующими данными везде, где он отображается.

Это лишь верхушка айсберга, когда речь идет об инновационных целях REST API. Однако давайте обсудим, как работает сам REST API.

Как работает WordPress REST API

Если кратко, то REST API работает посредством манипулирования текстовыми данными из одного места в другом без прямого доступа к базе данных или интерфейсу пользователя. Существует много типов API (Application Programming Interfaces), несмотря на это REST остаётся современным и актуальным стандартом .

REST API передаётся через точки доступа Hyper Text Transfer Protocol (HTTP), используя формат JavaScript Object Notation (JSON). Говоря проще, эти технологии обеспечивают доступ к API используя уникальные веб адреса для доставки данных, которые ведут себя как объекты JavaScript .

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

Какое значение WordPress REST API имеет для разработчиков

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

REST API базируется на JavaScript, внимание к которому всё возрастает, это намекает нам на то, какие языки программирования важно знать. Скоро вы обнаружите, что JavaScript стороны сервера – это новый PHP. Это уже может быть видно на новом ПО WordPress.com, Calypso , который работает полностью на JavaScript и REST API.

Стандартизируя, способ взаимодействия приложений (включая ядро WordPress) с данными WordPress, разработка под WordPress станет проще и интуитивно понятнее. Более того, это облегчит интеграцию со сторонними платформами.

Надеюсь, теперь у вас появилось больше аргументов в пользу того, зачем важно начать изучать использование этой технологии уже сейчас. Пришло время сделать первые шаги по использованию REST API в вашей собственной работе!

5 Шагов для старта с WordPress REST API

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

Для этого нужно открыть программу с интерфейсом командной строки (Command Line Interface CLI) на вашем компьютере – терминал на macOS или Linux и командную строку на Windows. CLI позволяет напрямую взаимодействовать с REST API, без необходимости писать дополнительные скрипты для запроса и обработки информации. Любой запрос, который вы пишете в CLI может быть сценарием на PHP, JavaScript и другом языке, но метод будет отличаться для каждого. В CLI прямое выполнение команд. Просто введите нужную команду и нажмите Enter.

Мы также рекомендуем настроить демонстрационный сайт или тестировать локально, а не пробовать эти шаги на живом сайте. И наконец, ещё все одно условие, чтобы версия WordPress у вашего сайта была 4.4 или выше. Если вы готовы, то давайте начинать!

Шаг 1: Знакомимся с основными понятиями REST API

Прежде чем начнём, давайте ознакомимся с ключевыми понятиями REST API . Всего пять основных понятий и терминов, с которыми следует познакомиться. Давайте их рассмотрим:

  1. Маршруты (‘Routes’) и Ресурсы или точки доступа (‘Endpoints’). Это наиболее важный аспект в понимании REST API. Маршруты помогают вам перемещаться между вашими ресурсами, когда определенный HTTP-метод (например, статический набор данных или действие) подключен к определенному маршруту. Например, /wp-json/ – это маршрут, настроенный как ресурс, созданный для отображения нам доступных маршрутов.
  2. Запросы (Requests). Они создаются путем запуска правильных ресурсов и прохождения данных.
  3. Ответ (Responses). Вкратце, предоставление данных, которые вы запросили или возвращение ошибки, чтобы дать вам знать, что что-то пошло не так.
  4. Схемы (Schemas). Ниже приведены ответы шаблонов, поэтому вы всегда точно знаете, где искать нужные данные.
  5. Классы контроллеров (Controller classes). Они позволяют создавать собственные маршруты и ресурсы. Пока вам не нужно беспокоиться об этом, они станут более полезными в дальнейшем.

Как только вы поймете эти пять концепций, вы можете начать углубляться в сам API REST, начиная с его точек доступа.

Шаг 2: Узнаём наиболее полезные точки доступа REST API

WordPress REST API предлагает reference handbook со всеми точками доступа (ресурсами), где вы сможете найти наиболее полезные для себя. Прежде всего, нужно знать, как построить HTTP-вызов API REST. Базовая часть любого вызова API-интерфейса WordPress выглядит следующим образом, замените yourdomain.com своим:

Http://yourdomain.com/wp-json/

Вы можете проверить соединение, выполнив команду curl в своем CLI, используя свой собственный URL-адрес:

Curl -X OPTIONS -i http://yourdomain.com/wp-json/

В ответ вас должно поприветствовать сообщение от HTTP . Дальше можно модифицировать эту команду, используя некоторые из главных ресурсов. Теперь мы просто используем версию GET curl.

Чтобы получить JSON список ваших публикаций в WordPress, можно использовать следующее:

Вслед за этим, попробуйте следующее, чтобы проверить все существующие страницы WordPress:

Curl -X GET -i http://yourdomain.com/wp-json/wp/v2/pages

Вы можете поэкспериментировать с каждой из этих точек доступа (и больше!) в CLI, чтобы рассмотреть какой ответ выдаёт каждый из них.

Шаг 3: Изучаем основы аутентификации REST API

Теперь самое время изучить аутентификацию. Некоторые действия и данные в REST API публичные, в то время как другие требуют, чтобы вы были авторизованы как администратор. Однако, это же REST API и негде входить в систему для авторизации. Вместо этого вы можете выполнить аутентификацию в процессе выполнения запросов, которые требуют админ доступа, таких как просмотр неопубликованных записей или изменение публикаций.

Начнём с установки плагина WordPress REST API Basic Auth . Это простой плагин для разработчиков, который поможет изучить REST API быстро, и не предназначен для реальных сайтов. Однако, процесс установки такой же как и у любого другого плагина.

Как только Basic Auth установлен, вы сможете выполнять аутентификацию через CLI с флагом user . Вот пример того, как применить метод аутентификации пользователя, используя curl для просмотра неопубликованных записей:

Curl -X GET --user username:password -i http://yourdomain.com/wp-json/wp/v2/posts?status=draft

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

Шаг 4: Выбираем свою первую публикацию WordPress при помощи REST API

Когда вы поймете, как делать базовые вызовы API REST с помощью curl, попробуйте выбрать конкретную запись. Вначале выведем все публикации, как мы это делали ранее:

Curl -X GET -i http://yourdomain.com/wp-json/wp/v2/posts

Вы можете использовать этот примем с добавлением ID для любого ресурса REST API, независимо от того, вы хотите отобразить публикацию, страницу или таксономию.

Шаг 5: Вносим изменения в публикацию в WordPress через REST API

И наконец, давайте попробуем внести изменения в выбранную вами публикацию. Вместо команд OPTION или GET , в этот раз будем использовать POST для внесения изменений. GET используется для чтения данных, в то время как POST – для их отправки.

Давайте переименуем вашу публикацию отправкой запроса POST вместе с данными для аутентификации. Новые изменения будут внесены с использованием флага d в конце команды. Будем передавать пользовательский JavaScript объект устанавливая переменную title на своё значение, такое как My New Title , как показано в коде ниже:

Curl -X POST --user username:password http://yourdomain.com/wp-json/wp/v2/posts/ -d "{"title":"My New Title"}"

Убедитесь, что вы заменили имя пользователя, пароль и ID публикации, а также название на свои. Вы можете выбрать ещё раз заданную публикацию для проверки изменений:

Curl -X GET -i http://yourdomain.com/wp-json/wp/v2/posts/

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

Заключение

WordPress REST API – новая мощная версия ядра WordPress и многие разработчики уже начали применять её возможности. Соответственно, ознакомившись сейчас с тем, как работать с новой возможностью, вы повысите свои программистские навыки и сможете создать приложение используя WordPress как фреймворк.

Напомним, мы прошли пять шагов на пути к изучению взаимодействия с WordPress REST API:

  1. Знакомство с основными понятиями REST API.
  2. Наиболее полезные ресурсы/точки доступа REST API.
  3. Изучение основ аутентификации REST API.
  4. Получение публикации на WordPress, используя REST API.
  5. Изменение публикации WordPress, используя REST API.

Какие у вас возникли вопросы по поводу WordPress REST API? Пишите нам в комментариях!