WordPress PHP filters allow you make a value modifiable from outside of your code. With the WordPress Block Editor (a.k.a. Gutenberg), you can now do the same thing in JavaScript.
applyFilters
The wp.hooks.applyFilters()
method allows you to expose your JavaScript value for modification. It takes the following arguments:
- the hook name, a unique identifier that allows targeting this value (e.g.
salcode.myLuckyValue
) - the default value, which is being made modifiable (e.g.
13
) - 0 or more additional values that can be used by the function hooking in to modify the value
WordPress JavaScript applyFilters
const luckyNumber = wp.hooks.applyFilters(
'salcode.myLuckyValue',
13, // Default value.
);
console.log( luckyNumber );
AddFilter
The wp.hooks.addFilter()
method does the actual modification of the value. It takes the following arguments:
- the hook name (again
salcode.myLuckyValue
) - the namespace, a string identifying the filter we are adding (
modifyingCodeAddedBySal
), this is used when removing a filter (removeFilter( 'hookName', 'namespace' )
) - the callback function, this function receives the current value as a parameter and returns the new value (additional values passed in from
applyFilters()
are passed to the callback here as well)
WordPress JavaScript addFilter
wp.hooks.addFilter(
'salcode.myLuckyValue',
'modifyingCodeAddedBySal',
(value) => 7
);
More about WordPress JavaScript Filters
See @wordpress/hooks
More About WordPress PHP Filters
I gave a talk on Making WordPress Filters Work for You at WordPress Lancaster 2017.
Leave a Reply