WordPress REST API v2 Examples

Here are a few examples on how to use WordPress REST API v2

First of all Download and Install the plugin just like any other wordpress plugin

Get list of posts

Get list of pages

WordPress REST API for Custom Posts

Prerequisite: REST API support needs to be added to custom posts while registering the custom post.

Below parameters add the necessary support. For detailed instruction please refer Adding REST API support to Custom Post Types

Suppose we have a Custom Post Type news, below parameters would add the necessary REST support to the Custom Post Type

show_in_rest

This allows the Custom post type to be accessed through the REST API

rest_base => Optional Parameter

This allows to change the REST API route. For e.g. if the custom post type is news. We can define a custom route to access the books post using rest_base parameter e.g. news_api

rest_controller_class

This is only required to be changed if you are using a custom namespace i.e. other than wp/v2

Once the necessary support is added as shown above the Custom Post Type is ready to be accessed through the REST API

Add REST support for custom taxomonies

Add below parameters to the custom taxomony newstags

Here are a few examples for a news custom post type

Get list all posts for the custom post type news

Get first 5 posts for the custom post type news

Get list all posts for the custom post type news from a certain category

Get a single post from the custom post type news

Get posts from the custom post type news which has custom taxonomy newstags applied to it

Modify JSON Response

WordPress Rest API provides us a filter rest_prepare_{POST_NAME} to modify JSON Response i.e. to add or remove fields from the JSON response. JSON response by default include many fields which may not be necessary for you. Also it may be missing some of your custom fields.

Add a custom field

 

Create a WordPress staging site through shell script

wordpress staging
Photo credit – 132889348@N0722868800432

Creating a wordpress staging environment requires 4 things. Here we are assuming that the staging environment is on the same server.

Requirements for creating a wordpress staging environement

  1. Clone Database – Each Time
  2. Copy the code – Only the wp-content folder
  3. Edit wp-config to point to the Staging Database (single site only) plus the Staging Domain (multisite) – Once Only
  4. Update the wp-options table with the Staging Domain (single site), Update the wp_blogs, wp_site, wp_options, wp_1_options, etc tables with the Staging Domain (multisite) – Each Time

So how to to achive creating a wordpress staging environement with a single script? Here are the steps.

Step 1: Create staging.sh and define variables

Create a file named staging.sh inside a directory named staging (preferably outside your public_html folder)

Define all the variables related to your production and staging database connection as shown below

Step 2: MySQL Dump of the Production database

Add below code to staging.sh file to get MySQL Dump of the current production database

Step 3: Export the Database to the Staging database

Again add below code to staging.sh. Here we are connecting to staging database and importing the sql file created in Step 2

Step 4: Batch File

Now create a new file within the staging directory named as batch.txt. Inside this batch file we will write all the queries we want to run to rename the production instances within the staging database to refer to the staging environment. The batch file will hugely depend on the type of site setup you have i.e. single site or multisite

If you have a single site then its very easy. Add below query to the file. Remember to replace PROD_DOMAIN and STAG_DOMAIN with the respective names. e.g. www.myproddomain.com

For mulsite it is bit complicated

Now just repeat the last time changing the number in wp_1_options to the number of the subsites

Step 5: Run the Batch file queries

To run the batch file queries add below code to staging.sh file

Step 6: Copy WordPress files

This can be done by a simple cp (copy command).

Step 7: Edit wp-config on the Staging

Now the last thing is to edit the wp-config file to point to the staging database. Thats all.

Finally just running the staging.sh script through SSH will set up the staging server.

Step 8: Weekly Cron Job

To refresh/update the staging server every week add cp command to staging.sh file and this time just copy the wp-content folder. You could also copy differences i.e. last changes only using rsync command.

Then set up a cron job to run staging.sh to run every week

 

How to selectively dequeue a script on individual post

Lot of plugins. Not sure what to do??

All of a sudden you may realise that you already have quite a lot of plugins on your website and probably some of those plugins are slowing your site down. That’s the point of time you may decide to review your plugins but at that point it is very difficult to imagine the impact of deactivating a certain plugin.

Here is a simple trick we can use to review our plugins and make sure atleast our important pages do not break.

Idea

The idea is to try and dequeue or remove a script on a page by page basis or post by post basic. Using this approach we are not deactivating the plugin on the entire site but we are just deactivating or removing it on just a single post or page. This way we can study the impact of removing the plugin on our most important pages/posts just so that we are sure it won’t break our site and we feel more comfortable to deactivate the plugin entirely on our site.

So how do we achieve this

Step 1: Print all the script handles used on a page/post

Step 2: Create a custom field

Create a custom field named wpi_selective_scripts_dequeue on our post/page and add bar separated (|) handles of the scripts which you wish to remove from the page (referring to list generated in step 1)

Step 3: Dequeue the script for that page/post

 

 

 

 

How to create wordpress options page

Creating WordPress options page in Dashboard for your own plugin is quite simple. Generally it is used to set global preferences for your plugin which you want to let the users customise as per their requirement.

We will create a settings screen by creating a class as that is the simplest way of creating your own options page for your custom plugin.

It can be done in 5 simple steps

  1. Declare Class for the settings Page
  2. Add the page in the settings menu
  3. Register your settings
  4. Create the backend options
  5. Finally generate the options page

Here is the entire code

Now we will discuss each function in detail

First of all we have named our class as someCustomPluginSettings

The constructor just calls the add_admin_menu function and initialises the settings registration

Below function creates the admin page.

Here we need to provide

  • Title of the settings page
  • Capability (this decides who will get access to this page). manage_options means editors and above can access this page.
  • Slug of the page

Below function registers the settings variables, description on the settings page, etc. The most important variable here is some_custom_plugin_settings. We will be using this variable to reference our stored data using the settings screen.

Below function creates the HTML objects to store our data. Please note that each field uses the same reference i.e.

some_custom_plugin_settings and stores the data in array i.e.

some_custom_plugin_settings[‘setting_1’], etc

Below function just renders the options page in a form

 

 

WordPress admin custom column sorting and filtering for custom post type

In WordPress Dashboard there are some default columns listed for any of your post types on the post listing page. We can sort our custom posts by Ascending or Descending order by just clicking these fields. However most of the times these fields are not enough.

E.g. if we create a custom post for books then we may need columns to sort or filter books by Year of publication, Author, Category, etc

So how do we create these extra columns for sorting and filtering

Assumptions

  1. Custom Post Type: book
  2. Year,  Author and Language information is stored in custom meta fields for each book

Se here are the steps

Step 1: Define the custom colums

Here we add two new columns to the admin panel of the custom post type book namely Publication Year and Author

Step 2: Fill Data to the columns

Here we are assigning data to the columns displayed in the custom post. Since the data is stored in the post meta we use get_post_meta function to get the data from the postmeta table.

Step 3: Define sortable colums

Here we are defining which columns are sortable. In our case we want all the columns to be sortable.

Step 4: Perform Sorting

Here we are using the request filterThis filter is applied to the query variables that are passed to the default main SQL query of the page. This filter adds additional parameters/filters to the query variable based on which the list of posts gets generated.

Until this step the additional columns are added to the custom post type listing page and they are sortable. They can be sorted by clicking the table heading as shown below

Additional columns

 

Step 5: Create Filters

This part of code can vary depending upon our configuration of custom fields and taxonomy. Main objective here is to create select boxes for the filters. Below approach shows how to create select boxes for data stored in custom meta fields. If the data is stored is categories then we may need to use wp_dropdown_categories function to list categories for the filter

Step 7: Perform Filtering

Here we are just altering the main query for the page by passing our own variables.

This will create filters as shown below

Custom Filter admin screen

12