If you want the accordion menu to only apply to specific parent categories (e.g., categories with specific IDs), you can filter the categories in the PHP code and include only those you want. Here's how you can achieve this:
Step 1: Specify the Target Parent Categories
Update the get_product_categories_with_count
function to include only specific parent categories by their IDs. For example, if you want to include categories with IDs 12
, 34
, and 56
:
function get_product_categories_with_count() { $target_parent_ids = [12, 34, 56]; // IDs of the specific parent categories $output = ''; return $output; } function build_category_item($category) { // Check if the category has subcategories $has_children = has_subcategories($category->term_id); $output = '
- ';
foreach ($child_categories as $child) {
$output .= build_category_item($child);
}
$output .= '
Step 2: Render the Menu in Your Theme
To display the menu, use the following PHP snippet where you want the menu to appear:
echo get_product_categories_with_count();
Step 3: Styling and JavaScript
The CSS and JavaScript remain the same as before. They will handle the toggle behavior and styling for the specific parent categories that you’ve selected.
.accordion-menu { list-style: none; padding: 0; margin: 0; } .accordion-menu > .category-item { position: relative; padding: 10px 15px; border-bottom: 1px solid #ccc; } .accordion-menu a { text-decoration: none; color: #333; font-weight: bold; margin-left: 10px; display: inline-block; } .accordion-menu .toggle-icon { position: absolute; left: 10px; font-size: 14px; font-weight: bold; cursor: pointer; } .accordion-menu .subcategories { list-style: none; padding: 0 20px; margin: 0; display: none; /* Initially hidden */ } .accordion-menu .subcategories .category-item { padding: 5px 0; border: none; /* No borders for subcategories */ } .accordion-menu .subcategories .toggle-icon { left: 20px; /* Indent for deeper layers */ }
JavaScript:
jQuery(document).ready(function($) { // Handle toggle functionality $('.accordion-menu').on('click', '.toggle-icon', function(e) { e.preventDefault(); // Prevent default action // Find the associated subcategories var subcategories = $(this).siblings('.subcategories'); if (subcategories.length > 0) { subcategories.slideToggle(); // Toggle the plus/minus icon var icon = $(this); if (icon.text() === "+") { icon.text("-"); } else { icon.text("+"); } } }); });
Step 4: Test the Menu
- Filtered Categories: Ensure only the specified parent categories and their respective subcategories are displayed.
- Toggle Behavior: Check that the plus/minus icons function correctly for the included categories.
- Nested Layers: Verify that deeper subcategories expand and collapse as expected.
This implementation ensures that only specific parent categories and their respective subcategories are included in the accordion menu. Let me know if you need additional refinements!
No comments:
Post a Comment