What is Action in WordPress?

  • Posted by: Editorial Team
  • No Comments

An action is one of the two types of hook that is triggered at a specific time when WordPress is running and lets you take an action. It provides a way for running a function at a specific point in the execution of WordPress Core, WordPress plugins, and WordPress themes. It is the counterpart to filters. This includes things like creating a widget when WordPress is initializing or sending a Tweet when someone publishes a post.

For example how it can be utilized to add code to a site let us expect that you need to add a copyright notice to your footer.

For doing this you could modify your footer template directly. In some cases, this would be desirable but many times it is much easier to hook your code to a predefined action that is already being executed in the footer. For doing this you can add your copyright code into a function in your functions.php file. You would then be able to add this function to an action that is in the spot where you might want your copyright code to be executed.

function copyright_notice() {

echo “Copyright All Rights Reserved”;

}

add_action(‘wp_footer’,’copyright_notice’);

Here in the above example, copyright_notice is an action hooked into the wp_footer hook. The function

Copyright_notice will be executed at whatever point the wp_footer() hook shows up in a WordPress theme code.

Types of Action

The WordPress Action Reference page has available actions listed by the following categories:

  • Actions run during a typical request.
  • Actions run during an admin page request.
  • Post, page, attachments and category options.
  • Comments, Ping and trackback actions.
  • Blogroll Actions
  • Feed Actions
  • Template Actions
  • Administrative Actions
  • Dashboard “Right Now” widget option.

How to add Action

Adding an action includes two steps:

First, you need to create a Callback function which will be called when the action is run.

Second, you need to add your Callback function to a hook which will perform the calling of the function, which can be done with the reference of WordPress Action Plugin Handbook.

Where you will use the add_action() function, passing at least two parameters, string $tag, callable $function_to_add.

Here, go through this example shown below which will run when the init hook is executed

<?php

function wporg_custom()

{

   // do something

}

add_action(‘init’, ‘wporg_custom’);

If you would like to hook in your own functions, the process is quite simple. First, you need to know a few pieces of information. For actions, you’ll want to know the name of the hook, as well as when exactly it runs. For filters, you also need to know the name of the hook, but you want to know what value you are going to get and have to return, as well. The final bit of information you need is the name of the function where you have all your code and you can add and remove action.



Leave a Reply

Call Now