• Skip to primary navigation
  • Skip to main content
Sal Ferrarello
  • About Sal Ferrarello
  • Speaking
  • Connect
    Mastodon GitHub Twitter (inactive)
You are here: Home / Dev Tips / Add Gutenberg JavaScript Filter

Add Gutenberg JavaScript Filter

Last updated on May 18, 2020 by Sal Ferrarello

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.

Sal Ferrarello
Sal Ferrarello (@salcode)
Sal is a PHP developer with a focus on the WordPress platform. He is a conference speaker with a background including Piano Player, Radio DJ, Magician/Juggler, Beach Photographer, and High School Math Teacher. Sal can be found professionally at WebDevStudios, where he works as a senior backend engineer.

Share this post:

Share on TwitterShare on FacebookShare on LinkedInShare on EmailShare on Reddit

Filed Under: Dev Tips, Programming, Solution Tagged With: Gutenberg, JavaScript, WordPress, WordPress Filter

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Copyright © 2023 · Bootstrap4 Genesis on Genesis Framework · WordPress · Log in