<?php
// Pre-select the first facet choice when this choice is unknown / different on each page the facet is placed on
// To pre-select a know choice, use the 'facetwp_preload_url_vars' hook instead:
// https://facetwp.com/help-center/developers/hooks/querying-hooks/facetwp_preload_url_vars/
add_action( 'facetwp_scripts', function() {
?>
<script>
document.addEventListener('facetwp-refresh', function() {
if ( !FWP.loaded ) { // Only on first page load
var facet_name = 'my_facet_name'; // Change 'my_facet_name' to the name of your facet
if ( 'object' == typeof FWP.facets[facet_name] && 1 > FWP.facets[facet_name].length ) {
var temp = document.createElement('div');
temp.innerHTML = FWP_JSON.preload_data.facets[facet_name];
var first = temp.getElementsByClassName('facetwp-radio'); // for a Radio facet, change if needed
first = first[1]; // Pre-select the second choice, skips the first "Any" choice. Use first[0] if there is no "Any" choice
FWP.facets[facet_name] = [ first.getAttribute('data-value') ];
FWP.loaded = 1; // force TRUE to make an AJAX request & populate results
}
}
});
</script>
<?php
}, 100 );
// Alternative: Pre-select using a page refresh with window.location.href instead of facet refresh
add_action( 'facetwp_scripts', function() {
?>
<script>
document.addEventListener('facetwp-refresh', function() {
if ( !FWP.loaded ) {
var facet_name = 'my_facet_name'; // Change 'my_facet_name' to the name of your facet
if ( 'object' == typeof FWP.facets[facet_name] && 1 > FWP.facets[facet_name].length ) {
var temp = document.createElement('div');
temp.innerHTML = FWP_JSON.preload_data.facets[facet_name];
var first = temp.getElementsByClassName('facetwp-radio'); // for a Radio facet, change if needed
first = first[1]; // Pre-select the second choice, skips the first "Any" choice. Use first[0] if there is no "Any" choice
FWP.facets[facet_name] = [ first.getAttribute('data-value') ];
let qs = FWP.buildQueryString();
let href = window.location.href
let prefix = (-1 < href.indexOf('?')) ? '&' : '?';
window.location.href = href + prefix + qs;
}
}
});
</script>
<?php
}, 100 );