WordPress移除script type属性适配Nu HTML验证遇阻求助
Hey, let's break this down. Your clean_script_tag function works great for most scripts, but the ones that are slipping through are likely not being loaded via WordPress' standard wp_enqueue_script function — which is exactly what the script_loader_tag hook targets.
Why some scripts aren't being modified
Lots of themes or plugins cut corners and hardcode <script> tags directly into template files (like header.php, footer.php, or custom template parts) instead of using WordPress' official enqueue system. Others might use custom output functions that bypass the script_loader_tag filter entirely.
Do you need to mess with wp-admin settings?
Short answer: No. WordPress admin settings don't control front-end script type attributes, and tweaking core admin settings here is unnecessary and risky — you could break backend functionality without fixing your original issue.
Fixes to try
Here are actionable steps to get those remaining scripts cleaned up:
Track down the rogue scripts
View your page's source code, find the<script>tags still carryingtype='text/javascript', and check theirsrcattribute or inline content to identify which theme/plugin is outputting them. Once you find the source file, you can manually edit the hardcoded tag to remove thetypeattribute.Enhance your filter to cover more cases
If manual edits aren't feasible (e.g., you don't want to modify plugin files directly), you can add a broader filter to scan and clean script tags in the final page output. Just be cautious — global replacements can have unintended side effects if not tested properly. Add this to your theme'sfunctions.phpor a custom plugin:add_filter('the_content', 'clean_all_script_tags'); add_filter('wp_footer', 'clean_all_script_tags', 999); // High priority to run last function clean_all_script_tags($content) { // Remove type attributes (handles both single and double quotes) $content = preg_replace('/type=(["\'])text\/javascript\1\s/i', '', $content); // Optional: Standardize quotes to double (matches your original function) $content = str_replace("'", '"', $content); return $content; }Test this thoroughly on a staging site first — some scripts might have inline code with single quotes that could break if replaced.
Use plugin-specific hooks (if available)
If the unmodified scripts come from a plugin, check if the plugin provides its own hooks to filter script output. This is a cleaner approach than global replacement, as it targets only that plugin's scripts without affecting the rest of your site.
内容的提问来源于stack exchange,提问作者Rushanthan

