WordPress更新导致functions.php自定义代码被覆盖,如何永久保留?
Hey there! I get it—having to re-add that code every time WordPress updates is a total hassle. Let's fix this properly so you never have to do that again.
Why Your Previous Fix Stopped Working
When you added the code directly to your theme's functions.php file, that file gets completely replaced every time your theme (or WordPress core) updates. That's exactly why your file protocol links broke again after the latest update.
Solution 1: Use a Child Theme (Recommended)
Child themes are built specifically to keep customizations safe during theme updates. Here's how to set one up:
- Step 1: Create a new folder in
wp-content/themes/named something likeyour-parent-theme-child(replaceyour-parent-themewith the actual folder name of your current active theme). - Step 2: Inside this new folder, create a
style.cssfile with this header (update the details to match your theme):
The/* Theme Name: Your Parent Theme Child Template: your-parent-theme */Templateline must exactly match the folder name of your parent theme—this tells WordPress which theme it's a child of. - Step 3: Create a
functions.phpfile in the child theme folder, and paste your custom code there:function allowed_link_protocols_filter($protocols) { $protocols[] = 'file'; return $protocols; } add_filter('kses_allowed_protocols', 'allowed_link_protocols_filter'); - Step 4: Go to your WordPress dashboard > Appearance > Themes, and activate your new child theme.
From now on, when your parent theme updates, your child theme's functions.php (and your code) will stay untouched.
Solution 2: Create a Custom Plugin
If you don't want to mess with child themes, a simple custom plugin works too—plugins aren't affected by WordPress or theme updates:
- Step 1: Make a new folder in
wp-content/plugins/calledallow-file-protocol. - Step 2: Inside that folder, create a file named
allow-file-protocol.phpwith this content:<?php /* Plugin Name: Allow File Protocol for Internal Links Description: Adds the 'file' protocol to WordPress's allowed link protocols so your internal resource manager links work. Version: 1.0 Author: Your Name */ function allowed_link_protocols_filter($protocols) { $protocols[] = 'file'; return $protocols; } add_filter('kses_allowed_protocols', 'allowed_link_protocols_filter'); - Step 3: Head to your WordPress dashboard > Plugins > Installed Plugins, find your new plugin, and click "Activate".
This plugin will run your code on every site load, and updates won't touch it.
Either of these methods will solve your problem for good. Child themes are great if you plan on making other theme-related customizations later, while plugins are perfect for standalone functionality like this.
内容的提问来源于stack exchange,提问作者Joe

