Actions & Filters In WordPress

8
Actions & Filters in WordPress

description

A very quick overview about Actions and Filters in WordPress

Transcript of Actions & Filters In WordPress

Page 1: Actions & Filters In WordPress

Actions & Filters in WordPress

Page 2: Actions & Filters In WordPress

Filters are functions that take in some kind of input, modify it and return it

Source: http://ottopress.com/2011/actions-and-filters-are-not-the-same-thing/

Page 3: Actions & Filters In WordPress

Actions are places where a function is called and we don‘t care what it returns.

In a sense, a Filter w/o args and return value

Source: http://ottopress.com/2011/actions-and-filters-are-not-the-same-thing/

Page 4: Actions & Filters In WordPress

In Core/** * Hooks a function on to a specific action. */function add_action( $tag, $function_to_add, $priority = 10, $accepted_args = 1 ) { return add_filter( $tag, $function_to_add, $priority, $accepted_args );}

/** * Hooks a function or method to a specific filter action. */function add_filter( $tag, $function_to_add, $priority = 10, $accepted_args = 1 ) { global $wp_filter, $merged_filters;

$idx = _wp_filter_build_unique_id($tag, $function_to_add, $priority); $wp_filter[$tag][$priority][$idx] = array( 'function‘ => $function_to_add, 'accepted_args' => $accepted_args ); unset( $merged_filters[ $tag ] );

return true;}

Page 5: Actions & Filters In WordPress

In a Plugin/** * Does something with the content */function my_custom_function( $content ) {

// Do something with the content

return $content;}add_filter( 'the_content', 'my_custom_function' );

Page 6: Actions & Filters In WordPress

In a Classclass My_Custom_Class {

/** * Construct */ public function __construct() {

add_filter( 'the_content', array( &$this, 'my_custom_method' )); }

/** * Does something with the content */ public function my_custom_method( $content ) {

// Do something with the content

return $content; }}

Page 7: Actions & Filters In WordPress

Plugin API in WordPress

Filter Functions has_filter() add_filter() apply_filters() current_filter() merge_filters() remove_filter() remove_all_filters()

Action Functions has_action() add_action() do_action() do_action_ref_array() did_action() remove_action() remove_all_actions()

Page 8: Actions & Filters In WordPress

In Core/** * Call the functions added to a filter hook. * Simplified */function apply_filters( $tag, $value ) { global $wp_filter, $merged_filters, $wp_current_filter;

// Dealing with 'all' filters and sorting

do { foreach( (array) current($wp_filter[$tag]) as $the_ ) if ( !is_null($the_['function']) ){ $args[1] = $value; $value = call_user_func_array( $the_['function'], array_slice($args, 1, (int) $the_['accepted_args']) ); } } while ( next($wp_filter[$tag]) !== false );

return $value;}