Skip to content

Instantly share code, notes, and snippets.

@ihslimn
Created January 3, 2024 18:59
Show Gist options
  • Save ihslimn/58ee2438a14068df3a26803f3203c4e2 to your computer and use it in GitHub Desktop.
Save ihslimn/58ee2438a14068df3a26803f3203c4e2 to your computer and use it in GitHub Desktop.
JetSmartFilters Set default value
<?php
class JSFC_Default_Value_Shortcode {
private $defaults = array();
private $script_enqueued = false;
public function __construct() {
add_shortcode( 'jsf_default_value', array( $this, 'do_shortcode' ) );
add_filter( 'jet-smart-filters/filter-instance/args', array( $this, 'apply_default' ) );
}
public function do_shortcode( $args ) {
$filter_id = absint( $args['filter_id'] ?? 0 );
if ( empty( $filter_id ) ) {
return;
}
$this->defaults[ $filter_id ] = $args['default'] ?? '';
$this->enqueue_script();
}
private function enqueue_script() {
if ( $this->script_enqueued ) {
return;
}
add_action( 'wp_footer', function() use ( $script ) {
?>
<script>
document.addEventListener( 'jet-smart-filters/inited', function( initEvent ) {
for ( const groupName in JetSmartFilters.filterGroups ) {
JetSmartFilters.filterGroups[ groupName ].currentQuery.update = 1;
JetSmartFilters.filterGroups[ groupName ].apply( 'ajax' );
}
} );
</script>
<?php
} );
}
public function apply_default( $args ) {
$filter_id = absint( $args['filter_id'] ?? 0 );
if ( isset( $this->defaults[ $filter_id ] ) ) {
$args['current_value'] = $this->defaults[ $filter_id ];
}
return $args;
}
}
new JSFC_Default_Value_Shortcode();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment