Actions & Filters In WordPress

Post on 13-Dec-2014

242 views 29 download

description

A very quick overview about Actions and Filters in WordPress

Transcript of Actions & Filters In WordPress

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/

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/

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;}

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' );

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; }}

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()

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;}