How to use $current_user or is_user_logged_in() with FacetWP and WordPress to show different content for logged-in users

I have a membership site where I need to display certain FacetWP results to people who are logged in and other FacetWP results to people who are logged out. Unfortunately, FacetWP forgets WordPress’ global $current_user variable the minute you use one of the facets. Same with WordPress’ is_user_logged_in() function – FacetWP forgets it all once you start filtering results.

Lucky for you, I invested my last 3 days researching this issue, trying many many potential solutions, before finding the following little bit of code, which you can throw into your functions.php file:

<?php
/*
  Force FacetWP to use $current_user and is_user_logged_in() when selecting facets.
  via https://facetwp.com/how-to-pass-authentication-data-through-rest-api-requests/
	
  Please note that caching may interfere with the NONCE,
  causing ajax requests to fail. Please DISABLE CACHING for facet pages,
  or set the cache expiration to < 12 hours!
*/
add_action( 'wp_footer', function() {
?>
<script>
(function($) {
  $(function() {
    FWP.hooks.addFilter('facetwp/ajax_settings', function(settings) {
      settings.headers = {
        'X-WP-Nonce': FWP_JSON.nonce
      };
      return settings;
    });
  });
})(fUtil);
</script>
<?php
}, 100 );
?>

Everything works great now! One thing: As the code comment mentions, be aware that this solution might cause issues with cache. [source]

Alternate Solution: Page Refresh when facets are selected

FYI: An alternate and less-elegant solution to this same problem of FacetWP forgetting whether or not the current website visitor is logged in is to use a full page refresh every time a facet is selected. This is clunky, is a resource hog, but works in need! In fact, I almost went to press with this solution (until I discovered the more-elegant solution above). Add the following snippet to your functions.php to force a page refresh every time a FacetWP facet is selected:

<?php
/*
  Refresh the whole page every time a FacetWP facet option is changed.
  via https://gist.facetwp.com/gist/force-a-page-reload-on-facet-interaction/
*/
add_action( 'wp_footer', function() {
?>
<script>
document.addEventListener('facetwp-refresh', function() {
    if (FWP.loaded) {
        FWP.setHash();
        window.location.reload();
    }
});
</script>
<?php
}, 100 );
?>

[source]

Is this helpful?

Posted in

Toby Cryns

Toby Cryns is a freelance CTO, expert WordPress consultant, and teacher.

He offers free advice to improve your freelance biz.

He also publishes small droppings every now and then to twitter.com/tobycryns and twitter.com/themightymo

Follow Toby's contributions on Github and WP.org.