Overview

With this hook, introduced in FacetWP v4.2.2, you can inject custom code snippets (JavaScript, CSS) into the page footer, only on pages where FacetWP is active.

This hook is an alternative to using the wp_footer hook, which runs on all pages. Using the facetwp_scripts hook instead prevents JavaScript errors when injecting FacetWP-dependent custom code, like code using FacetWP’s fUtil libary.

Usage examples

Add custom JavaScript to the footer, only on pages where FacetWP is active:

How to use custom PHP code?

PHP code can be added to your (child) theme's functions.php file. Alternatively, you can use the Custom Hooks add-on, or a code snippets plugin. More info

add_action( 'facetwp_scripts', function() { ?> <script> // Your custom JavaScript code </script> <?php }, 100 );

Add custom CSS to the footer, only on pages where FacetWP is active:

How to use custom PHP code?

PHP code can be added to your (child) theme's functions.php file. Alternatively, you can use the Custom Hooks add-on, or a code snippets plugin. More info

add_action( 'facetwp_scripts', function() { ?> <style> /* Your custom CSS code */ </style> <?php }, 100 );

Prevent JavaScript errors when using fUtil code

If you use the wp_footer hook to inject custom code that contains JavaScript that is dependent on code that is loaded only on pages where FacetWP is active, like FacetWP’s fUtil library, you’ll get JavaScript errors on pages where FacetWP is not loaded. Using facetwp_scripts instead prevents these errors.

For example, say your site does not load jQuery, and you want to use the fUtil libary to add a class to the .facetwp-template element, like this:

How to use custom PHP code?

PHP code can be added to your (child) theme's functions.php file. Alternatively, you can use the Custom Hooks add-on, or a code snippets plugin. More info

add_action( 'wp_footer', function() { ?> <script> (function($) { $('.facetwp-template').addClass('my-class'); })(fUtil); </script> <?php }, 100 );

The above code will cause fUtil not defined errors in the Console on all pages without facets. Using the facetwp_scripts hook will prevent these errors:

How to use custom PHP code?

PHP code can be added to your (child) theme's functions.php file. Alternatively, you can use the Custom Hooks add-on, or a code snippets plugin. More info

add_action( 'facetwp_scripts', function() { ?> <script> (function($) { $('.facetwp-template').addClass('my-class'); })(fUtil); </script> <?php }, 100 );

Note that if you have code using fUtil that you want to run on non-FacetWP pages, you’ll have to load the fUtil library independently on those pages.

See also

Last updated: December 14, 2023