WordPress 代码片段大全:50 段最常用的 functions.php 实用代码(收藏直接用)
在 WordPress 主题的 functions.php 文件中放置自定义代码,是扩展功能和修改行为最直接的方式。以下收集了 50 个最常用、经过测试的代码片段,覆盖了安全、性能、后台优化、前端修改、用户管理等各个方面。你可以根据自己的需要,复制粘贴到子主题的 functions.php 中使用。
后台优化类
-
移除后台不需要的菜单项:
add_action('admin_menu', 'remove_admin_menus');
function remove_admin_menus() {
remove_menu_page('edit-comments.php'); // 评论
remove_menu_page('tools.php'); // 工具
}
-
修改后台页脚版权信息:
add_filter('admin_footer_text', 'change_footer_admin');
function change_footer_admin() {
echo 'Powered by <a href="https://wordpress.org">WordPress</a>';
}
-
禁用后台帮助标签页:
add_action('admin_head', 'remove_help_tabs');
function remove_help_tabs() {
$screen = get_current_screen();
$screen->remove_help_tabs();
}
-
移除 WordPress Logo 并替换为自定义 Logo:
add_action('admin_bar_menu', 'replace_wp_logo', 999);
function replace_wp_logo($wp_admin_bar) {
$wp_admin_bar->remove_node('wp-logo');
$wp_admin_bar->add_node(array(
'id' => 'custom-logo',
'title' => '我的网站',
'href' => home_url(),
'meta' => array('title' => '访问首页')
));
}
-
禁用文章修订版本(保留最近的 5 个):
define('WP_POST_REVISIONS', 5);
或完全禁用:define('WP_POST_REVISIONS', false);
前端修改类
-
更改摘要“阅读更多”文本:
add_filter('excerpt_more', 'new_excerpt_more');
function new_excerpt_more() {
return '... <a class="read-more" href="' . get_permalink() . '">继续阅读 »</a>';
}
-
设置摘要长度(字数):
add_filter('excerpt_length', 'custom_excerpt_length');
function custom_excerpt_length($length) {
return 30;
}
-
移除 WordPress 版本号(安全):
remove_action('wp_head', 'wp_generator');
-
移除 Emoji 脚本(加快加载速度):
remove_action('wp_head', 'print_emoji_detection_script', 7);
remove_action('admin_print_scripts', 'print_emoji_detection_script');
remove_action('wp_print_styles', 'print_emoji_styles');
remove_action('admin_print_styles', 'print_emoji_styles');
-
禁用 XML-RPC 接口:
add_filter('xmlrpc_enabled', '__return_false');
-
禁用 REST API 的非认证访问(可选):
add_filter('rest_authentication_errors', function($result) {
if (!is_user_logged_in()) {
return new WP_Error('rest_forbidden', '请登录', array('status' => 401));
}
return $result;
});
-
给所有外部链接添加 nofollow:
add_filter('the_content', 'add_nofollow_to_external_links');
function add_nofollow_to_external_links($content) {
preg_match_all('/<a\s+.*?href=["\'](http[s]?:\/\/[^"\']+)["\'].*?>/i', $content, $matches);
if (!empty($matches[0])) {
$site_url = home_url();
foreach ($matches[0] as $link) {
if (strpos($link, $site_url) === false && strpos($link, 'nofollow') === false) {
$new_link = str_replace('<a', '<a rel="nofollow" target="_blank"', $link);
$content = str_replace($link, $new_link, $content);
}
}
}
return $content;
}
安全类
-
禁止通过 ?author=n 枚举用户名:
add_action('wp', 'disable_author_enumeration');
function disable_author_enumeration() {
if (isset($_GET['author']) && is_numeric($_GET['author'])) {
wp_die('禁止访问', 403);
}
}
-
登录错误提示不区分用户名还是密码:
add_filter('login_errors', 'generic_login_error');
function generic_login_error() {
return '用户名或密码错误';
}
-
限制登录尝试次数(简化版,建议配合插件):
add_action('wp_login_failed', 'track_login_failures');
function track_login_failures($username) {
$ip = $_SERVER['REMOTE_ADDR'];
$failures = get_transient('login_failures_' . $ip);
if (!$failures) $failures = 0;
$failures++;
set_transient('login_failures_' . $ip, $failures, 600);
if ($failures >= 5) {
// 锁定 15 分钟
set_transient('login_locked_' . $ip, true, 900);
}
}
-
隐藏后台“外观”菜单(非管理员不可见):
add_action('admin_menu', 'hide_menu_for_non_admin');
function hide_menu_for_non_admin() {
if (!current_user_can('administrator')) {
remove_menu_page('themes.php');
remove_menu_page('plugins.php');
remove_menu_page('users.php');
remove_menu_page('tools.php');
remove_menu_page('options-general.php');
}
}
性能优化类
-
移除 jQuery Migrate 脚本:
add_action('wp_default_scripts', 'remove_jquery_migrate');
function remove_jquery_migrate($scripts) {
if (!is_admin() && isset($scripts->registered['jquery'])) {
$script = $scripts->registered['jquery'];
if ($script->deps) {
$script->deps = array_diff($script->deps, array('jquery-migrate'));
}
}
}
-
延迟加载 CSS 和 JS(简化处理,建议用插件):
add_filter('style_loader_tag', 'add_defer_to_styles', 10, 2);
function add_defer_to_styles($tag, $handle) {
return str_replace('rel=\'stylesheet\'', 'rel=\'preload\' as=\'style\' onload="this.onload=null;this.rel=\'stylesheet\'"', $tag);
}
-
移除不必要的
wp_head项:
remove_action('wp_head', 'rsd_link');
remove_action('wp_head', 'wlwmanifest_link');
remove_action('wp_head', 'wp_shortlink_wp_head');
remove_action('wp_head', 'rest_output_link_wp_head');
remove_action('wp_head', 'feed_links_extra', 3);
-
禁用加载 Google Fonts(如果主题自带):
add_filter('wp_enqueue_scripts', 'remove_google_fonts', 100);
function remove_google_fonts() {
wp_dequeue_style('open-sans');
wp_deregister_style('open-sans');
}
用户与登录类
-
允许上传 SVG 文件:
add_filter('upload_mimes', 'allow_svg_upload');
function allow_svg_upload($mimes) {
$mimes['svg'] = 'image/svg+xml';
return $mimes;
}
-
自定义登录页面 Logo:
add_action('login_enqueue_scripts', 'custom_login_logo');
function custom_login_logo() {
echo '<style>#login h1 a { background-image: url(' . get_stylesheet_directory_uri() . '/images/logo.png) !important; }</style>';
}
-
登录页面 Logo 链接改为网站首页:
add_filter('login_headerurl', 'custom_login_logo_url');
function custom_login_logo_url() {
return home_url();
}
-
注册成功后自动登录并跳转:
add_action('user_register', 'auto_login_after_registration');
function auto_login_after_registration($user_id) {
wp_set_current_user($user_id);
wp_set_auth_cookie($user_id);
wp_redirect(home_url());
exit;
}
-
限制某个角色只能看到自己的文章:
add_action('pre_get_posts', 'restrict_author_view');
function restrict_author_view($query) {
if (is_admin() && !current_user_can('administrator')) {
global $user_ID;
$query->set('author', $user_ID);
}
}
实用工具类
-
获取当前页面 URL:
function current_page_url() {
global $wp;
return home_url(add_query_arg(array(), $wp->request));
}
-
获取文章阅读时间:
function reading_time($post_id) {
$content = get_post_field('post_content', $post_id);
$word_count = str_word_count(strip_tags($content));
$minutes = floor($word_count / 200);
return $minutes . ' 分钟阅读';
}
-
给标题不足 15 个字的文章自动补充后缀:
add_filter('the_title', 'add_title_suffix', 10, 2);
function add_title_suffix($title, $id) {
if (!is_admin() && strlen($title) < 15) {
$title .= ' - 详细指南';
}
return $title;
}
-
防止直接访问 PHP 文件(放在 functions.php 头部):
if (!defined('ABSPATH')) exit;
-
清除不需要的 body_class 类:
add_filter('body_class', 'remove_body_classes', 10, 1);
function remove_body_classes($classes) {
$remove = array('page-id-1', 'single-format-standard');
return array_diff($classes, $remove);
}
以上只是 30 条示例(篇幅原因先给出 30 条核心的,剩余 20 条适合放在第二篇中)。你可以将这些片段整理成一个文档,需要时直接复制。唯一需要注意的是:避免一次性添加太多不理解的代码,最好每添加一条就测试一遍网站前后台功能,确保没有冲突。安全保留至少两份备份:一份代码片段库,一份完整网站备份。

