WordPress Hooks, filters and actions

WordPress Hooks, filters and actions

2572289473_f24c6561fc_z

What are wordpress Hooks

WordPress Hooks provide the ability to enhance, modify or customise a wordpress functionality by writing your own code without modifying the wordpress core code.

A WordPress Hook code can either be written directly in your themes (preferably child theme’s) functions.php or by creating your own plugin (recommended way)

Types of hooks

There are 2 types of wordpress hooks

  1. action hooks: These hooks can also be called as trigger hooks as they gets triggered based on a certain action/event. e.g. when a user registers on your site an action hook can be set up to geocode the user address and add the latitude longitude to the user_meta table.
  2. filter hooks: This hook allows to enhance or modify wordpress functionality or data e.g. it allows to use a custom template for certain post types, allows to use your custom page for lost password functionality, filter user data before displaying on browser or storing in the database.

Examples of hooks

user_register action hook: This action hook allows you to access data for a new user immediately after they are added to the database. The user id is passed to hook as an argument.

template_include filter hook: Allows to select custom template for your custom post types

 

Reference

List of action hooks

List of filter hooks

 

Creating Custom hooks for your own plugin

Creating your own custom hooks is also possible so that other developers can extend and modify it, without having to fork it.

Read more on how to create custom hooks

 

 

WordPress Custom Login page

Creating a WordPress custom login page has 2 benefits

  1. Login page can be created based on your own theme
  2. The URL for the login page would be different to the WordPress login URL. This is a good security practice provided you block the Wordpress default login page or redirect it to your custom login page.

This does not mean that you need to create your own methods to store and retreive cookies by creating your own login function. WordPress provides easy to use functions using which you can create own own plugin to create a wordpress custom login page.

So here is the sample login form

WordPress custom login page – form

Here the form action submits to a page which does the authentication part. If you have created your own plugin the page would most likely be in your plugin folder.

Here is the page which does the authentication and sets the cookie

WordPress custom login page – authentication

wp_authenticate authenticates the user. If ok wp_set_auth_cookie sets the cookie for the user

 

Automatic Database backups using free Sypex Dumper tool

Photo credit – williamhook2631871046

Automatic database backups can be set up very easily using a simple shell script and a cron job. However it may not be a practical solution for huge databases and the restoration process can also be difficult. There are various tools available to make this process simple. Sypex Dumper is just one of them.

What is Sypex Dumper

Sypex Dumper is a software product (PHP-script), which can help you create a backup copy (dump, export) of a MySQL database, and also restore the database from the backup file if needed. Read more and download

With this tool huge databases can be backed up and restored with very high speed using least server resources and greatly reducing the size of the database dumps.

Free version of the tool is enough to create the automatic backups. The Paid version allows to selectively restore a particular table from the entire database.

Steps to set up automatic Database Backups

Let’s assume you want to create backup of your database every day and keep the recent 30 backups on your server

Create the required job in SXD

1. Login to Sypex Dumper with your database user credentials

Setup automatic database backups using Sypex Dumper

2. Click on the Export option

3. Select the database from the Database drop down

4. Since we want to keep only the last 30 database backups add 30 in the Autodelete If number of files more than box.

5. Add some comments e.g. Last 30 backups

6. Clicking the Save button will create the backup job with the name specified

Create the shell script to execute the job

Now that the job is created we want to execute it using a shell script. Here is a sample script

Automate the script

Finally just add the above script to a cron job so that it runs once daily

 

 

MySQL archive records based on date column

Photo credit: 27892629@N04 - cc
Photo credit: 27892629@N04cc

Let’s assume you have a logs table and you want to delete the logs which are more than 1 year old.

Ideally you would like to automate this using a cron job.

MySQL Between query

Using the above query we can delete all the logs for the year 2014. However we cannot automate this query since we are providing the dates manually.

MySQL DATE_SUB query

Above query deletes all the records which are older than a year. Here we do not need to provide dates. It automatically finds the records which are older than a year using NOW and INTERVAL parameters.

So let’s say you want to delete all the records which are 6 months old then the query would be

Now lets automate the process of archiving our logs table

This can be done through a number of ways.

Shell Script

A shell script can be created with above code. The script can then be added to a cron job.

MySQL event scheduler

Read more

PHP Script

Create a PHP page to run the query and then create a cron job for the PHP page

A php script is the most recommeded system in this case because deleting records does not need lot of memory and it is easier to manage the PHP Script.

WordPress XMLRPC attacks – How to prevent

Wordpress XMLRPC

What is wordpress XMLRPC

RPC stands for Remote Procedure Call. WordPress XMLRPC is a protocol which allows remote systems to communicate with WordPress. The language to communicate is XML.

With WordPress XMLRPC support, you can post to your WordPress blog using many popular Weblog Clients.

XML-RPC functionality is turned on by default since WordPress 3.5.

Brute Force Attack through wordpress XMLRPC

Attackers user system.multicall method in XML-RPC to create hundreds of request combined in a single request to attack a system i.e. mostly to guess the username and password to the system. This is called as Brute Force Amplification Attacks  via WordPress XML-RPC

How to prevent XMLRPC attack

  1. The most recommended way is to disable XML-RPC completely. To disable XML-RPC completely add following to your APACHE configuration file.
  1. Some plugins in wordpress e.g. Jetpack is based on XML-RPC. In that case it is not possible to disable XML-RPC entirely. In that case you can disable system.multicall requests through your firewall
  2. Check server logs regularly and find IPs trying to access XML-RPC. Any suspicious IP can be blocked through your Firewall or iptables. Here are some sample logs

     

Mandrill decides to discontinue service as a separate product

Mandrill has decided to discontinue their service as a separate product and is becoming a transactional email add-on to paid MailChimp accounts.

This means the free 15000 emails/month service which Mandrill offered will soon be no longer available. All Mandrill users will be required to have a paid monthly MailChimp account.

Here are the timelines

  • Starting March 16, all new Mandrill users will create accounts through MailChimp.
  • Also starting March 16, Mandrill users can merge their existing Mandrill account with a MailChimp account.
  • Current users will have until April 27 to merge the accounts.

So what are the alternatives:

Generally Mandrill is used to send transactional emails like password reminders, notifications, etc taking the load off your own webserver. There are quite a few services which allow to send such transactions emails

  1. Amazon SES (this is the option recommeded by MailChimp)
  2. MailGun (10,000 emails/month free)
  3. SendGrid (12,000 emails/month free)

Moving wordpress site to a new server

Moving wordpress site or  any other site requires transferring atleast below mentioned files and settings to the new server

  1. Code and Media files residing in your public_html directory
  2. Database
  3. Cron Jobs
  4. Any Back up scripts or other shell scripts, snippets, config files, etc residing outside your public_html directory

Some hosting companies like Siteground also provide free website transfer. However for number of reasons like complexity or security you may decide to perform the migration yourself.

Below steps explains moving wordpress or any site from one server to another without using FTP or without requiring to download an upload files on your PC.

Here are the steps for moving wordpress site

1. Clean up your old server and remove any unnecessary files or directory

2. Create a tar file from the entire public_html directory contents

SSH to your legacy server and run below command

3. Create an SSH key

To accept data from the legacy server, an SSH key from the legacy server is required to be added to the known hosts file on the new server. This key can be directly appended to the text in the known hosts file if you have access to it or some hosting providers provide a panel to add the key and to restrict the connection from certain IP addresses. Here you can provide the legacy server IP address.

The above command will generate dsa key. You can create either RSA or DSA key. Some hosting companies only accept certain type of key.

After running the above command the key will get created in your .ssh directory. Copy the contents of the public key and add them to the new server to accept connections from the legacy server

4. Moving wordpress public_html folder contents

Above command will copy the public_html contents from the legacy server to the new server’s public_html directory. You will required to Unarchive the contents on the new server.

5. Export database on the legacy server

Here you can use utility of your choice or you can just create a mysqldump of your database. If you are using some utility like SXD then create a copy of database on the legacy server using SXD.

Then move the database to the new server using below command

6. Import the database on the new server

First create a blank database on the new server and then import the database. If you have database backup created using SXD then install SXD on the new server and import the database on the new server through SXD.

7. Other Data (outside public_html)

If the data is not too much you can just tranfer this data using FTP or follow the same process as explained in Step 4

8. Cron Job

Lastly create similar cron jobs on the new server and check if they are working

 

Adding a plugin textdomain / translation into wordpress

A plugin textdomain is required if you need to translate your own plugin in different langauges i.e. to internationalize the plugin.

Here are the required steps

Step 1: Decide the plugin textdomain name

e.g. my_plugin_textdomain

Step 2: Initialise the languages directory for the plugin textdomain

Add below code to your plugin

Create languages folder within your plugins directory.

Step 3: Create PO file for the languages

If you are creating a language translation for German then you would need to create a po file with below name

my_plugin_textdomain-de_DE.po

Download a sample PO file

Open the file in a suitable text editor and add the necessary translations in the file

Step 4: Create MO file

Once all the translations are added to the PO file open the file in Poeditor and just save the file. Poeditor will automatically create corresponding mo file. Upload both the files on your plugin languages folder

 

For the translation to show up for the corresponding words or phrases __(“sample text”) is to be used within the plugin code.

When to use Database Triggers ?

What are Database Triggers ?

A Database trigger is an SQL code which is made to run just before or after a certain event. That event could be an INSERT, UPDATE or a DELETE query on a particular database table.

Thus a trigger is used to automate some of the events on your server/site/application.

Examples of some Database triggers

  1. Sync user details from one table to another when a user updates them
  2. Geocode users location and store them in a separate table
  3. Maintaing log of certain events e.g. a product addition, updation or deletion (In this case we wish to know who did the change)

When to use Database triggers

There are few pros and cons about using database triggers.

Pros:

  1. Yes they can automate quite a lot of activities
  2. For things like maintaining logs if you are doing this through your code then most probably you need to add the piece of code in a number of files. e.g. If you are maintaing a log about article updates then there may be a number of files in your code related to updating articles. You will need to add the log related code in every file. But if this is done through trigger then you do not need to worry about updating your code.
  3. In the above example if the log table structure changes then you just need to update your trigger code and you are done.
  4. Triggers are very handy in case you have completely different systems on different platforms and coding is not really possible. This is mostly the case in large organisations.

Cons:

  1. Since the trigger is not part of your normal code it may create lot of confusion later as to how certain things are happening especially if you are new to the system and things are not properly documented. Due to this lot of people prefer to write event driven procudures in their code instead of creating triggers as that way they are in full control of the application.
  2. If the business logic changes then the triggers can be difficult to handle/update. At that point of time it may happen that a certain event may not be possible through a trigger and you may need to revert back to your usual way to handling events through your code. This may further increase development time.

Conclusion

Based on the above pros and cons we can understand that using a trigger or not is not really a straightforward decision. It really depends on case by case basis.

  1. If you are coding in an object oriented manner then most probably you are writing all your events in structured manner and there is no duplication of code. In that case it becomes quite easy to add the event based procedures within your code.
  2. However in some cases the code is not object oriented as it may be quite an old application. In that case you can make a judgement call whether its the time to update the code or create triggers.
  3. In case 2 if the code is done by some other developer then it is likely that you would use triggers.
  4. For applications built on different platforms or different scripting languages sharing common resources triggers can be handy to achieve some form of integration.

 

 

 

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