In simple word's.
Actions are those PHP functions which execute the output.
Filters are those PHP functions which return the output.
Updated: We can extend any plugin which use the actions and filters without modifying there code. By adding filters and actions in our own theme or plugin.
How to use?
Action:
Check below simple examples in your theme functions.php
file.
- Example One: (Simple PHP example)
function test() {
echo "Output";
}
test();
Above program print the output:
Output
[NOTE: Here test() simply call the function. And execute the callback function 'test'.]
- Example Two: (Simple use of Action)
function test1() {
echo "Output";
}
add_action( 'test', 'test1' );
do_action( 'test' );
Above program print the output:
Output
[NOTE: Here do_action('test')
works like calling function. And execute callback function 'test1'.]
- Example Three: (Another use of Actions)
function test2() {
echo "Test 2";
}
add_action( 'test', 'test2', 1 );
function test1() {
echo "Test 1";
}
add_action( 'test', 'test1', 2 );
do_action( 'test' );
Above program print the output:
Test 2Test 1
[NOTE: Here do_action('test')
works like calling function. And execute callback functions on it's priorities.
Callback function 'test1' has priority 2 And 'test2' has priority 1. ]
If priorities are change like 'test1' with priority 1 And 'test2' with priority 2 then output will be:
Test 1Test 2
- Example Four: (3rd party support)
Add below code in
functions.php
function test1() {
do_action( 'test_before' );
echo "Test 1";
do_action( 'test_after' );
}
add_action( 'test', 'test1' );
do_action( 'test' );
Above program print the output:
Test 1
Now, Create sample plugin to check how it works for 3rd party Developer.
- Create folder 'simple' in
/wp-content/plugins/
directory.
- Create file named 'simple.php' and add below code.
/*
* Plugin Name: Simple Plugin
*/
function test_callback_function() {
echo "From plugin";
}
add_action( 'test', 'test_callback_function' );
Now, Activate our Simple plugin from WordPress admin dashboard.
Goto menu plugin and activate it.
After activate plugin above program print the output:
Test 1From plugin
[NOTE: If we add the priority for our plugin action from 1 to 9 then it print the output like:
From pluginTest 1
Because, WordPress consider the 10 priority by default
for all the added actions.]
Filters
Check the below examples:
Simple PHP example:
$data = array( 'one', 'two' );
print_r( $data );
Above program print the output:
Array ( [0] => one [1] => two )
- Example One: (Simple use of Filter)
$data = apply_filters( 'my_filter_name', array( 'one', 'two' ) );
print_r( $data );
add_filter( 'my_filter_name', function( $old_data ) {
return array( 'three', 'four' );
});
Above program print the output:
Array ( [0] => three [1] => four )
Here, We have added filter my_filter_name
and change the existing output array( 'one', 'two' )
with array( 'three', 'four' )
without changing the theme/plugin files.