Twenty Seventeen子主题按分类切换配色方案失败求助
Fixing Category-Based Color Scheme Switch in Twenty Seventeen Child Theme
Let's walk through the issues with your code and fix it step by step:
Key Problems in Your Original Code
- Typo: You wrote
is_category( 'x cateorgy' )—note the misspelling of "category" (extra 'o'). That’s definitely preventing the condition from triggering correctly. - Incorrect Scope: You’re adding
colors-darkoutside theifblock, so it gets appended to every page’s body classes, not just the target category. - Inefficient Class Removal: While the loop works, we can simplify removing the
colors-customclass with cleaner array operations.
Corrected Code
Here’s the revised version that addresses all these issues:
add_filter( 'body_class', function( $classes ) { // Replace 'x-category' with your actual category slug/name/ID if ( is_category( 'x-category' ) ) { // Remove 'colors-custom' if it exists in the classes array $key = array_search( 'colors-custom', $classes ); if ( false !== $key ) { unset( $classes[$key] ); } // Add the dark color scheme class $classes[] = 'colors-dark'; } return $classes; }, 1000 );
Important Notes
- Category Identifier: Use the category’s slug (e.g.,
x-category) instead of the name for better reliability—slugs are consistent and case-insensitive. If you prefer using the name, make sure it’s an exact match (including spaces and capitalization). - Priority: The
1000priority ensures your filter runs after the parent theme’s body class setup, so you’re modifying the classes after they’ve been added by Twenty Seventeen. - Testing: After updating the code, visit your category page and inspect the
<body>tag in your browser’s developer tools. You should seecolors-darkinstead ofcolors-customin the class list.
Adding More Color Schemes Later
When you want to add additional category-specific schemes, you can extend the code with elseif conditions:
add_filter( 'body_class', function( $classes ) { // Remove default custom color class first if needed $key = array_search( 'colors-custom', $classes ); if ( false !== $key ) { unset( $classes[$key] ); } // Add category-specific color classes if ( is_category( 'x-category' ) ) { $classes[] = 'colors-dark'; } elseif ( is_category( 'y-category' ) ) { $classes[] = 'colors-light'; } elseif ( is_category( 'z-category' ) ) { $classes[] = 'colors-accent'; } else { // Fallback to default custom colors if no category match $classes[] = 'colors-custom'; } return $classes; }, 1000 );
This version first removes the default colors-custom class, then applies the appropriate scheme based on the category, with a fallback to the default if none match.
内容的提问来源于stack exchange,提问作者Krustylicious
相关产品推荐
相关产品推荐

