API plugin. WordPress REST API - what is it for and what is it? api plugin

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:

Today we're going to be talking about the WordPress REST API (some people call it the JSON REST API), an upcoming addition to the WordPress core that's now available as a plugin and was originally released in version 4.1. Now we are waiting for two-stage integration in versions 4.4 and 4.5. If the developers are very enthusiastic about the appearance of this new feature, then the average WordPress user may not understand all this excitement, although the appearance of this feature can be called a milestone in the history of WordPress. Let's find out what the WordPress REST API is, what it means for the future of WordPress, and why it's capitalized.

What is an API?

Let's start with the basics and terminology, as the name of the JSON REST API is made up entirely of acronyms. The first three letters of “API” stand for Application Programming Interface.

What is the API for?

Basically, the API is needed to connect different pieces of software, and you can think of it like a USB port.

USB ports are used for communication various types devices with your computer. These can be printers, computer controls, portable hard drives, phones, and so on. Through this port, a computer and a device can interact with each other, exchanging information. API is something similar, only it connects not devices, but programs. Thus, programs can exchange data within a strictly defined framework, interacting with each other. You are constantly using the API without even noticing it. For example, if you use third party programs to use your Twitter account, this action is performed via the Twitter API. Thanks to API technology, I can be on Twitter every day without even going to the Twitter site.

The API is also required when you use email marketing services like MailChimp on your WordPress site. In short, an application programming interface allows developers to use the features and data of other web applications or services for their own software in a completely secure way.

What does REST and JSON mean?

REST is short for Representational State Transfer. REST describes a specific API architecture designed to be lightweight, user friendly, and suitable for a wide range of services. Google, Facebook, and Twitter use a REST style for many of their APIs, for the simple reason that REST is based on HTTP, the protocol that is ubiquitous on the web, along with its more secure cousin, HTTPS. Due to its high compatibility with modern technologies, REST-based APIs are gaining popularity on the web, and not just in the case of WordPress. Almost any program that has internet access can use this type of API. It looks like it brings great opportunities for program interaction, doesn't it?

JSON is a text-based data exchange format based on JavaScript. The peculiarity of JSON is that it is a human- and machine-friendly format. Developers can write and read it like a normal programming language, and computers can easily parse and generate it. Be that as it may, its most important advantage is that the main programming languages ​​already have encoders and decoders to convert the data structure to JSON or vice versa. This means that the JSON interface can act as a kind of translator between two applications that were written in different languages, and otherwise could never interact with each other.

The JSON format can become something of a universal connector on the Internet, and for this reason, WordPress and other large services have decided to take advantage of this. On top of that, in WordPress, JSON also replaces the slightly outdated XML-RPC standard, which is more difficult to use.

From all of the above, the following conclusions can be drawn:

  • API is a connector on any software;
  • REST is the design of this connector;
  • JSON is a cable with universal plugs at the ends;

JSON REST API and WORDPRESS

Okay, we realized that this thing is useful. But doesn't WordPress already use these APIs in its framework? Well, yes, there is one, and that is the WordPress API. It is used for WordPress plugins and only works with internal WordPress processes. But if we are talking about interaction with software from the outside, this API is outdated and not very user friendly. The new WP API is much more versatile as it is designed to allow WordPress to easily interact with other websites and services on the internet. Using the universal API, you can display and save content from other sites and applications, regardless of whether they use the WordPress engine or not. That's right, this API allows the WordPress platform to become a content management system suitable for any application written in any language.

Plus, the same thing works in reverse. Everything on your WordPress site will also be available on any external website and service, including:

  • Records;
  • Pages;
  • Custom post types;
  • media;
  • Comments;
  • taxonomies;
  • Users;
  • And much more

It works because it's based on HTTP, which is available everywhere. The protocol allows sites to send, create, read, update, or delete requests between two parties. In HTTP, POST, GET, PUT, and DELETE commands are equivalent. In addition, the API understands URLs whose structure is similar to directories, and as we know, similar links are just used by WordPress and other content management systems.

Summarizing what has been said, it is mono to say that if you want to transfer all records of a certain user from your site to another resource, then you can simply use the directive -

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

The same goes for updating single posts, deleting users, publishing pages, and more. In short, the API allows you to manage the WordPress admin area without the need for manual authorization and use non-WordPress content.

Great, but is it safe? The good news is that the WordPress REST API has built-in security measures. The magic word here is authentication. The interface has both cookie authentication and OAuth authentication. So cookie authentication works for plugins and themes, while OAuth is used to authenticate mobile, web and desktop clients. Both methods limit third-party activities on your site. Since the APIs are designed to allow platforms to exchange strictly defined information in a limited way, your data is completely safe.

What does the WP API for WORDPRESS mean?

Is this one of those things that only developers can use? How will this change affect the average site user? Adding the WordPress REST API is the first step in making WordPress a complete web application platform, as it opens up the WordPress platform to interact with the entire web.

As mentioned above, the APIs allow you to do the same things that the WordPress admin panel allows you to do, but without bypassing user interface. This means that the WordPress backend is no longer needed.

  • Any developer can create an alternative WordPress admin panel based on virtually any device or platform.
  • The new API could bring many alternatives to the standard backend, including mobile applications available for WordPress administration
  • Since JSON support is natively built into iOS and Android, the monopoly of WordPress apps will be history.
  • Third party content will also be available to WordPress. And what's more, the API makes WordPress content independent of the programming language and environment, so you can take content from any source and display it however you want.
  • Ruby on Rails and other frameworks will have access to the functionality of WordPress with all the features that come with it, and the benefits of these areas will become available to WordPress users.

This news will especially please developers who work with the front-end, as they will be able to change the front-end as they please, without affecting the back-end.

For non-developers, this technology can be used to create new solutions and integrate content from other web profiles with their WordPress sites.

WordPress enters a new era

WordPress will not only make new types of content available, but thanks to the new API, WordPress content will be available to the entire web. Non-PHP based systems will be able to use WordPress data, adapting it with their own applications.

But the most interesting thing is the possibility of using WordPress products, such as plugins, on other platforms and content management systems.

Mobile apps built on top of WordPress will be available everywhere, which is great news for anyone who builds or uses them. I think that there will be solutions that will allow the average user to automatically create mobile applications based on WordPress sites.

Eventually:

As you can see for yourself new wordpress The REST API transforms WordPress into something new. It will open WordPress to the entire Internet, and allow the platform to interact more seamlessly with third-party applications and services. The appearance of the WordPress REST API will please not only developers, but also ordinary users, which will receive many new features.

A plugin is a dynamically loaded library (DLL). After installing the program, all plugins included in the distribution are placed in the directory c:\Program Files (x86)\Common Files\Soft Gold\Inventory 14\Plugins\... The *.abl extension is required for automatic download plugin from the specified directory when the application starts. The plugin can also be loaded from any other location on the disk by specifying the search path in the settings.

Plugin API initialization

(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

// getting a unique window class name with parameters

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

// finding the window itself

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

If PluginsHostWnd<>0 then

Begin

// getting the atom string to get the xml document parameter

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

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

If Assigned(XMLDocRef) then

Begin

// adding an element to the list

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

// initialize the address of the Invoke function

ClientRef.ChildValues["Invoke"] := IntToId(Integer(@Invoke)); // hexadecimal $XXXXXXXX

end;

end;

end;

initialization

CoInitialize(P);

InitializeDoc;

Setting up and running the demo version of the plugin

The demo version of the plugin is configured automatically during installation of the program and is connected immediately after launching Inventory. The package includes the source code of the component (project name sgPlugin.dpk) and the demo version of the plugin (project name plug1.dpr ).

To run the plugin from debug mode:

▪ Open C:\Users\USER_NAME\Documents\Inventory 14\Plugins\Source\Delphi\Demos\Plug1\plug1.dpr

▪ Set in project options:

Search Path : "..\..\Components\PlugItem";

Output deretory , for example: "c:\Program Files\Common Files\Soft Gold\Inventory 14\Plugins";

Host application , on again installed application, for example: "c:\Program Files\Soft Gold\Inventory 14\Inventory 14.exe".

▪ Run for execution.

To use the component at designtime, you need to open, rebuild and install C:\Users\USER_NAME\Documents\Inventory 14\Plugins\Source\Delphi\Components\PlugItem\sgPlugin.dpk. After installing the component, the TsgPluginItem component will appear in the Delphi component palette, on the Soft Gold tab, which can be used at designtime, i.e. put on the form.

Excellent for ERP integration

This plugin is EXCELLENT, very useful to sync nopCommerce with ERP systems. It is, however, not complete and a little published. Download the source code and sample application from GitHub to add missing code.

MY PERSONAL EXPERIENCE

I used it for a customer that has been running a physical store for years and has only recently asked me to create the eCommerce site.
He already has a highly customized ERP system for maintaining commerce data, with more than 300 tables, including products and customers.
So nop commodities, although nop, although they did not have the same
I said I honestly didn't know, I'd take one day to do some analysis, see what plugins were available and give him a more precise estimate by the end of the day.
Luckily I found this amazing plugin, downloaded the source code and accompanying sample. The API is easy to change as you simply mimic the database structure to provide any missing functionality. The sample is tougher as it's very basic, but it does show how to call the API functions and how the token authentication mechanism works.
This is what I personally did:
1) Copied the sample MVC web application on a server on the intranet with IIS and created a CNAME record so that it could be accessed as http://nopSync
2) Gave it the same "look and feel" as the nopCommerce Admin panel by doing "view source" and referencing most of the same css files
3) Removed the login form and session variables, hard coded credentials in web.config and automatically authenticated on load
4) Used a SQL script to insert SKU and Manufacturer for all nopCommerce products. These two combined fields were my key to uniquely match products between the two systems
5) The api provides a "list" function to select all products but updates are performed one by one.
I could have read all the products and then with a loop accessed the ERP system each time, checking the price and quantity and updating nopCommerce if there were differences.
However, I considered it more performant to read all the nopCommerce data into a local database PRODUCTS table with a DoesItRequireUpdating flag by default equal to false.
The benefit of this was that the ERP system would only be accessed once. With a single query on the PRODUCTS table using a JOIN on ERP database tables I was able to update PRODUCTS prices, quantites and flags and subsequently call the update API once for each product with flag set to true.
6) I allowed for both manual and automatic syncronization. Manual by inserting a link to http://nopSync in the Admin panel menu and automatic by using a scheduled task to repeatedly call the web sample.

When the customer asked me, at the end of the day, how many days it would take to build the ERP syncronization, I said that thanks to SevenSpikes API plug it was online and syncronizing. Thanks SevenSpikes!!

  1. The Complete Guide to Customizing the WordPress API, Part 1: An Introduction

Now is the time to become a professional WordPress developer. Whether it's custom development or the creation of themes and plugins, today there is a demand for everything related to this topic.

WordPress has a well-written developer API documentation regardless of their level of training. But this does not eliminate the need to accumulate practical experience in the field of development for this CMS.

As with most things in web development, just because something works doesn't mean it's done absolutely right. Therefore, we, as developers and kind of artisans, are puzzled by making sure that what we do is done right.

Plenty of theme and plugin source codes show that developers keep doing what works, but it's far from being done in the most efficient way. This is especially true for theme options, menu pages, validation mechanisms, and the like.

And we want to stop it.

In this article series, we're going to take a deep dive into the heart of the WordPress Settings API. We will understand what the issue is and why it is important, as well as learn how to use this API correctly.

Our main goal is to learn how to competently configure the Settings API (Settings Programming Interface, hereinafter Settings API), regardless of your level of experience. By the end of the series, you will have gained a deep, holistic understanding and practical examples of how to use this API correctly in practice.

To successfully pass all the stages, we need to start from absolute zero. Before writing any code and analyzing examples, we need to get acquainted with the Settings API - find out what it is and what it is intended for.

Definition of the term "Settings API"

At its core, the Settings API is a set of functions provided by WordPress that simplifies the process of creating menus, settings pages, and storing, validating, and retrieving user input.

Sounds simple, doesn't it?

In this series of articles, we will explore each aspect in detail. And we can build on this simple definition in our further work.

Why should you use the Settings API?

After we figured out what the Settings API is, let's see why we are going to use it instead of our own written procedures for processing user input, serialization (the process of turning any data structure into a sequence of bits) and validation.

Engagement with WordPress Core

The Settings API was developed by the creators of the WordPress platform to make it easier to create extensions. Therefore, it is quite logical to use the functions provided by this API.

Of course, you can bypass the Settings API and brute-force your own functionality without anyone being able to stop you, but doing so requires extra work and can lead to non-compliance with the recommendations of the WordPress core team, which can eventually lead to errors in the control panel.

Using a tool made by developers for developers ensures that we interact with the kernel in the right way.

Free standard features

Using the Settings API is not only a guarantee that development will be carried out the right way. Also, it is the assurance that the user interface will follow the traditions of the platform, and the data will be processed by mechanisms similar to those used in WordPress itself. Plus, it can save you a lot of time.

When you start building your interfaces the same way WordPress does and use the Settings API in your work, your products will be tightly integrated with the CMS.

This means that when users work with your creations, they will feel at ease - everything will be clear to them. They will feel like they are modifying a system plugin created by the WordPress developers.

In truth, using native WordPress styles is not directly related to the Settings API and is a slightly different topic, but the menu page aspect of the Settings API involves using native WordPress styles.

Doesn't it make sense to stick to a single style?

More secure, more sustainable

By taking advantage of WordPress' built-in functions, you can be sure that the save, retrieve, and validation procedures will run smoothly. The Settings API provides many functions that are safe for the kernel to use.

After all, the Settings API follows the same rules and principles as the WordPress API. Also, when the CMS is updated, the Settings API functions will also be deprecated. You will need some time to update your project BEFORE the incompatibility affects it.

What's next?

Now, you should have a general idea of ​​what the Settings API is and why you should use it when creating themes and plugins.