In your category.php file, try replacing this:
<?php get_sidebar(); ?>
With this conditional check:
<?php // Check category and parent category for matching sidebar
$cat_id = get_query_var('cat'); // Get ID of current category
$cat_term = get_term_by( 'id', $cat_id, 'category' ); // Use ID to get category data
$cat_slug = $cat_term->slug; // Get category slug from data
$cat_parent_id = $cat_term->parent; // Get parent category ID from data
$cat_parent_term = get_term_by( 'id', $cat_parent_id, 'category' ); // Use ID to get parent category data
$cat_parent_slug = $cat_parent_term->slug; // Get parent category slug from data
if ( is_active_sidebar( $cat_slug ) ) { // Check for active widgets in sidebar that matches category slug
get_sidebar( $cat_slug ); // Load sidebar file that matches category slug
} else if ( is_active_sidebar( $cat_parent_slug ) ) { // Check for active widgets in sidebar that matches category parent slug
get_sidebar( $cat_parent_slug ); // Load sidebar file that matches category parent slug
} else { // Default if no sidebars match
get_sidebar(); // Load default sidebar file
} ?>
That code adds a lot of variables to get the category and parent category slugs and is a bit complicated, so I added some comments so that you could understand how it is working better.
Basically it will check for sidebar with an ID that matches the category slug, if it finds one and that sidebar has widgets, it loads a sidebar file with that category slug. If there isn’t a match, it checks the category’s parent for a sidebar and attempts to load that. If all else fails, it loads the default sidebar.
This code assumes that the category slugs, sidebar IDs, and sidebar file names all match, like this:
- Category Slug: category-1
- Sidebar ID: ‘id’ => ‘category-1’,
- Sidebar File: sidebar-category-1.php
I hope that helps!