The question:
Note: This is more of a tutorial/wiki than a real question and should be a reference for later Questions. If you got something to add, please feel free to add an answer. Working answers get upvoted. π
Scenario
You want to modify the output of some wp core function and instead of modifying the core directly (which is always bad), you have found a call like this:
$filterable_var = apply_filters( 'name_of_filter', $filterable_var );
The filter function allows you to modify eg. $filterable_var
and therefore the output of the wp function.
The Problem
You donβt know what exactly the function wants as input.
The Tags
Check what you can modify.
Possibly Related Q:
[Fell free to add your own Questions here.]
The Solutions:
Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.
Method 1
Example
Nav menu walker β allows adding eg. css classes to (all) menu items.
// copyied from /wp-core/wp-includes/nav-menu-template.php > line 76 (wp 3.1.1) - start_el() function
$class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args ) );
Now letβs check the $var:
function wpse15319_check_nav_menu_classes( $classes )
{
// You can take any of the $vars from the core function above: $classes, $item, $args
echo '<pre>';
// nice list:
print_r( $classes );
// or check of what type the $var is
var_dump( $classes );
echo '</pre>';
return $classes;
}
add_filter( 'nav_menu_css_class', 'wpse15319_check_nav_menu_classes', 10 );
Modify β Applied example
function wpse15319_add_nav_menu_classes( $classes )
{
$classes[] = '';
$classes[] .= 'my added css classes';
return $classes;
}
add_filter( 'nav_menu_css_class', 'wpse15319_add_nav_menu_classes', 10 );
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0