Skip to content

Instantly share code, notes, and snippets.

@MWDelaney
Last active March 12, 2019 17:38
Show Gist options
  • Save MWDelaney/31720c2cac8316a689ddbdd32c3e4072 to your computer and use it in GitHub Desktop.
Save MWDelaney/31720c2cac8316a689ddbdd32c3e4072 to your computer and use it in GitHub Desktop.
Rewrite the HTML output of radio buttons into a Bootstrap dropdown
<?php
// Adjust FacetWP "Radio" HTML output to be friendlier with our theme
add_filter('facetwp_facet_html', function ($output, $params) {
// Check that this facet is a "radio" type facet before proceeding.
if ('radio' == $params['facet']['type']) {
// Initialize our variables
$output = '';
$buttons = '';
$selected_label = '';
// Get the selected values for the facet
$selected_values = (array) $params['selected_values'];
// Get all the values for the facet
$values = (array) $params['values'];
// Loop through the values and create our dropdown items, marking them as "checked" or "disabled" as needed
foreach ($values as $key => $result) {
// Write the markup for each button, this example comments out the "counter" span
$buttons .= sprintf(
'<button class="dropdown-item facetwp-radio %s" data-value="%s">%s</button>',
in_array($result['facet_value'], $selected_values) ? ' checked active' : '', // If this item is selected, add the "checked" and "active" classes
$selected .= (0 == $result['counter'] && '' == $selected) ? ' disabled' : '', // If this item is disabled, add the "disabled" class
$selected_label .= in_array($result['facet_value'], $selected_values) ? esc_html($result['facet_display_value']) : '', // Get the label of the selected item so we can use it for the dropdown trigger button text
);
}
}
// Write the markup for the dropdown
$output = sprintf(
'<div class="dropdown">
<button type="button" class="btn btn-light btn-block dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
%s
</button>
<div class="dropdown-menu w-100">
%s
</div> <!-- /.dropdown-menu -->
</div> <!-- /.btn-dropdown -->',
($selected_label) ? $selected_label : $params['facet']['label_any'], // Set the selected label, or set it to the default
$buttons,
);
// Return the whole darn thing
return $output;
}, 10, 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment