Empty trash hook in wordpress

In some cases we may want to delete data related to certain post stored in some custom table (i.e. data which is currently not in wordpress).

If the data related to a post is not in wordpress then it won’t get cleaned once the post is deleted from the wordpress and you may end up garbage and unmanageable data in your custom table.

e.g. we have a custom post to register attendees to our events. There is also a need to log if the user had attended previous events too and to maintain their preferences for each year/event. Since it is not possible to store such yearwise/eventwise data in wordpress through custom fields, we may end up creating our own custom table.

The requirement is when the user gets deleted from the system, the data stored about the user in the custom table should also get deleted

WordPress provides a hook to clean such data stored in your custom table.



How to create wordpress custom filter hook

How to create wordpress custom filter hook

Wordpress custom filter hook

This is just an example explaining how to create a wordpress custom filter hook

Let’s say you have a page or a plugin displaying posts/custom posts based on a certain criteria

Now you wish to provide a hook to the end user to be able to modify how the posts get displayed.

Here is a sample code to display posts using a standard wordpress loop

Note that we have displayed the  posts after getting the contents in a variable named $wpi_snippet_view. This helps us to define a hook to be able to modify this variable.

Below code shows how to define our custom filter hook

The only difference is the above code is line number 19 where we have defined the custom hook as wpi_snippet_view_hook

Now that the custom hook is defined, all we need to do is to call the hook in our functions.php and modify the variable $wpi_snippet_view to show the required output.

Using the above hook we have changed the thumbnail size from thumbnail to large. You can change the view completely as per your requirements. Using the above hook you can present dynamic posts in various ways on the same page.

Server load monitoring tools for your wordpress site

Server load monitoring tools for your wordpress site


Here are some basic tools which will allow you to monitor server load to keep your wordpress site optimised.

Uptime (shell command)

Above command is an example of the uptime command. It says the server is up since 364 days, 2 users are logged in and the rest of the numbers are showing the server average load. The three numbers show the load averages for the last minute, 5 minutes and 15 minutes.

If you have 4 CPUs and the load is 2 then your server is using half the CPU capacity.

If you have 2 CPUs and the load is 2 then your server CPU is running at full capacity.

A load above the number of CPUs means that the system is overloaded which reduces performance.

top (shell command)

top command shows information like tasks, memory, cpu and swap. Here is a sample output of the top command.

Server monitoring

PHP sys_getloadavg function

sys_getloadavg function returns an array.

In above code, $load[0] would be the server load value.

Based on the above code we could even stop Dashboard access temporarily for all your editors if the load increased to a certain limit. Just add below code to your functions.php

If the server load reaches above 0.8 then all your editors and admins would be redirected to your home page expect the users having the capability as high_load_dashboard_access.

So only users having the above capability can access the system to try and monitor what is going on.

This is quite useful in cases you are experiencing heavy load on the server and editors are not able to upload or edit content and keep refreshing the page thereby causing extra load unnecessarily on the server.

Monyt App

Install Monyt App on your mobile. Its quite easy to configure. Depending on your device and server just add the necessary server monitoring file on the server and provide its URL within your app.

The file on the server runs some server monitoring commands and creates a json file which you can password protect. Simply add this file URL to Monyt app.

How to prevent WordPress CSRF attack

How to prevent WordPress CSRF attack

WordPress CSRF attack happens the same way as it happens on other sites. WordPress provides some inbuilt tools to protect against CSRF. We will see how to make use of these tools while creating our own wordpress plugins.

Wordpress CSRF Attack
Photo credit – 2508581015littleblackcamera

What is CSRF ?

CSRF meansCross-Site Request Forgery (CSRF). It is a type of attack that occurs when a malicious web site, email, blog, instant message, or program causes a user’s web browser to perform an unwanted action on a trusted site for which the user is currently authenticated.

How does it happen ?

For e.g. if you have a form on your website and you haven’t protected it for CSRF attacks then a hacker can create a similar form elsewhere and trick one of your users to submit the form. This means the hacker can fill any values in the form. The damage depends on the functioning of the form.

How to prevent CSRF

In short, to prevent CSRF attack all we need to do is to check if the right user is performing the right action on your website.

WordPress CSRF attack and Nonces

WordPress has inbuilt facility called as Nonces to prevent such attacks. Basically nonce is some code (mix of letters and numbers) which is automatically generated and sent as a hidden field in the form. This number is then compared with the number on the submit page and further action allowed only if both the numbers match. This number has limited lifetime and keeps changing after every regular interval i.e. after the lifetime of that particular nonce for that user has reached. Although the hacker could see this number in your source code the number would not be valid as it depends on the user and it keeps changing.

However wordpress nonces are not the only solution to prevent CSRF. We also need to check user permissions before executing a certain action.

CSRF protection on your forms

Some form fields here In the above form the function wp_nonce_field creates a hidden field with some nonce string.

Below code goes on your submit form action/page

On the submit page the nonce value in the hidden field is validated using the function wp_verify_nonce then only the form gets processed.

CSRF protection on your AJAX calls

Prevent wordpress csrf  attack by protecting your Ajax calls too. jQuery calling an unprotected PHP page can have severe security implications.

Here is how we can apply CSRF protection on Ajax calls

Below code goes on your PHP page

check_ajax_referrer verifies the AJAX request to prevent processing external (malicious) requests.

Show custom field validation errors in WordPress Admin

Show custom field validation errors in WordPress Admin

Wordpress Admin Notices

If you are creating your own custom post type in wordpress and you use some custom fields to store data related to each post.

For e.g. if you create a custom post for events then you would store data like event start date, end date, address, etc within custom fields.

Unless all the all required custom fields are filled you do not want to publish the event and so you would want to warn the event editor about it.

WordPress admin_notices hook allows to achieve this very easily

admin_notices is the hook available to display the messages

add_settings_error – Registers the setting error to be displayed to the user

settings_errors – This function simply displays all the errors line by line

Setup wordpress cron jobs and debug methods

Setup wordpress cron jobs and debug methods


Why would you need to setup WordPress cron jobs ?

Cron jobs in WordPress can be set for following reasons

  1. You have a custom post type for events and you wish to archive all your old events at regular intervals
  2. Archive logs e.g. if you have some plugin which tracks user activity then you may want to archive the logs table at regular intervals
  3. If you have integrated wordpress with some external application e.g. a mailing server then you need to synchronise your mailing lists with the external server
  4. Clearing caches for certain pages

How to setup wordpress cron jobs

wp_schedule_event is the function used to set up wordpress cron jobs

Here’s a sample code to set up a cron job

The above code will execute the function wpi_some_cron_job on daily basis. Some of the other options are hourly, twicedaily

Now the question is where do we add the above code. The answer to this depends whether you want to set this up as part of your own custom plugin or this cron is just some adhoc function which you wish to execute for housekeeping purpose e.g. clearing expired transients in your wp_options table.

Here is the code to add the cron job in the activation hook of your own plugin

Here is the code to add the cron job within your functions.php

If you have added the code to the activation hook of your plugin, it needs to be deactivate once the plugin is deactivated. Here’s how you deactivate.

Debugging WordPress Cron jobs

A. Try triggering the WordPress cron engine manually by opening below URL in your browser


B. Turn on WP_DEBUG on your development environment by adding below line in your wp-config.php file

C. Create some custom field for debugging purpose and set the custom field to increment every time through a cron job runs. Then check if the field gets updated.

How to tackle WordPress slow queries

How to tackle WordPress slow queries

Photo credit – elisfanclub859241997

Here are some wordpress slow queries i.e. queries which take more than 0.05s. It really depends on your wordpress site i.e. how big is the database, plugins and your site configuration. However if you are facing performance issues related to the Dashboard then it is more likely to be due to the slow wordpress dashboard queries.

Query Monitor is good plugin to check/analyse your slow queries.

Some WordPress Slow queries

Below query auto populates the custom fields drop down box.

For large tables this query can take lot of time like 2secs or so. If you do not need custom fields it is very easy to turn them off using below function.

For more information read this interesting post on CSS Tricks

Below query runs on every Dashboard page so it is important that your wp_options table is optimised.

Depending upon the plugins you have installed, the wp_options table size can grow rapidly. Some plugins use this table to store _transient options. These _transient options are objects stored in cache. For e.g. a plugin called as Manual Related Posts stores related links per post in separate rows as _transient options. So if you have 50K posts there would be 50K rows in this table. The size of the table can also grow rapidly because each row would atleast be 1M in size.

The table structure is also not optimised properly for e.g. option_id column is defined as bigint type, autoload is set to var. It should have been set as boolean or enum. Depending upon the table size and other configurations it can even take 8secs to run above query which is quite alarming.

Few tips to optimize wp_options table

  1. Check for _transient entries and if possible replace the plugins which create lot of _transient entries. Please note that although the purpose of these entries is for caching, since this table runs crucial queries on all Dashboard pages, it defeats the purpose for large wordpress installations. The table structure also does not help the cause.
  2. If it is not possible to replace the plugins creating lot of _transient entries then use the Transient Cleaner plugin which will delete the expired transient entries and will automatically do the housekeeping for you.
  3. Change the table structure a bit. Add autoload column to the list of indexes, change the option_id to int (12)

How to apply Sendgrid categories to WordPress emails

Sendgrid Categories

What are Sendgrid Email Categories

Creating categories for different kinds of emails sent through sendgrid is quite beneficial. It allows you to track emails based on each category i.e. it allows you to tag your emails by topics.

e.g. it would be nice to know

  • how many user registration emails actually were delivered,
  • how many people requested password resets, etc

For instance emails sent through wordpress can be categorised as

  1. User Registration
  2. Password Reset
  3. Newsletter, etc

How to add Sendgrid categories

As per the sendgrid documentation

You can add categories to the X-SMTPAPI header of the emails you send via SendGrid. This will allow you to track emails based on your own categorization system.

In case of wordpress emails here are the steps to follow

  1. Install the WordPress Sengrid plugin: Since the version 1.6.9 this plugin allows to add categories in the email headers.
  2. add the category headers to the wp_mail function as shown below

How to add category headers to the wp_mail function

The above headers can be added to your custom plugins where you define your own wp_mail function.

However in case of wordpress internal emails e.g. User Registration Confirmation email you would need to first customise that email to be able to add the required headers. For instance here is a nice link which shows how to customise User Registration Confirmation Emails

Sendgrid Category statistics

Once the required headers are added sengrid can shows statistics based on each sendgrid categories as shown below


Sendgrid Category statistics


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


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


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.