The Beans Filters API extends the WordPress Filters API by registering sub filters if it is told to do so.
Sub-filters are useful when its value need to be filtered with more specificity for a specific scenario. It can be seen as an HTML element which is globally styled and specifically styled for one scenario by adding and extra CSS class.
Don’t worry if it doesn’t make much sense at this stage, sub-filters seems a bit tricky to understand at first but it is actually very easy and logical. The pratical examples further down should give a great understanding of how the Beans filters works and how useful they are. First things first, let’s take a look are to apply Beans filters
Applying filters and sub-filters
Filters are applied using beans_apply_filters() and sub-filters must be in between square brackets as follow.
$value = beans_apply_filters( 'hook[_sub_hook]', 'value' );
The line above would creates two filters, hook and hook[_sub_hook]. If the same had to be done using the WordPress core apply_filters(), it would be as follow.
$value = apply_filters( 'hook', 'value' );
$value = apply_filters( 'hook[_sub_hook]', $value );
Also note how the first filtered value is passed to the second filter. The example below illustrates where the power of sub-filters lies.
Example
Let’s assume a date format filter needs to be modified for all posts, only for the page posts or only for a certain post id. Below is how the filters would be applied.
$post_type = get_post_type();
$post_id = get_the_ID();
$format = beans_apply_filters( "my_date_hook[_{$post_type}][_{$post_id}]", 'Y-m-d' );
date_i18n( $format );
Note how the $post_type and $post_id are added in between square brackets to create sub-filters. From there, the date format can be changed globally as follow.
beans_add_filter( 'my_date_hook', 'my_function_name' );
function my_function_name( $format ) {
return 'm/d/Y';
}
It can also be applied to pages only, by adding [_page] to the base filter hook as follow.
beans_add_filter( 'my_date_hook[_page]', 'my_function_name' );
function my_function_name( $format ) {
return 'm/d/Y';
}
And finally, it can be modified for a specific post id (68 for the example below), by adding [_68] to the base filter hook.
beans_add_filter( 'my_date_hook[_68]', 'my_function_name' );
function my_function_name( $format ) {
return 'm/d/Y';
}