Home / eCommerce / Search Filter by Genre and Artist
Duplicate Snippet

Embed Snippet on Your Site

Search Filter by Genre and Artist

This will only work if genre and artist are registered as taxonomies in your theme or plugin.

If you’re not sure those taxonomies exist, I can help you register them.

Code Preview
php
<?php
add_action( 'pre_get_posts', 'softcomplexmusic_custom_search_filter' );
function softcomplexmusic_custom_search_filter( $query ) {
    if ( !is_admin() && $query->is_main_query() && $query->is_search ) {
        $tax_query = [];
        if ( !empty($_GET['genre']) ) {
            $tax_query[] = array(
                'taxonomy' => 'genre', // Ensure this matches your site's taxonomy slug
                'field'    => 'slug',
                'terms'    => sanitize_text_field( $_GET['genre'] ),
            );
        }
        if ( !empty($_GET['artist']) ) {
            $tax_query[] = array(
                'taxonomy' => 'artist', // Ensure this matches your site's taxonomy slug
                'field'    => 'slug',
                'terms'    => sanitize_text_field( $_GET['artist'] ),
            );
        }
        if ( !empty($tax_query) ) {
            $query->set( 'tax_query', $tax_query );
        }
    }
}

Comments

Add a Comment