WordPress常用代码大全 包括安全/功能/美化等常用代码

WordPress是一个流行的CMS平台,具有强大的社区支持和灵活的自定义功能。在使用过程中,你可能需要添加一些自定义代码来增强网站的功能,如定制主题、自定义页面模板等。以下是一些常用的WordPress代码,可以帮助您在定制网站时更快的实现所需功能。 WP2整理了很多在WordPress开发中的常用代码,将代码放入执行文件(例如:functions.php)中就行,便于大家查阅,不断更新中...


锚点:#WordPress安全 #WordPress功能 #WordPress加速优化 #WordPress美化

WordPress安全

1. WordPress禁止自动更新

define("AUTOMATIC_UPDATER_DISABLED", true); // 禁用自动更新 wp-config.php 

add_filter("pre_site_transient_update_core", "fake_update_callback"); // 关闭核心提示  
add_filter("pre_site_transient_update_plugins", "fake_update_callback"); // 关闭插件提示  
add_filter("pre_site_transient_update_themes", "fake_update_callback"); // 关闭主题提示

remove_action("admin_init", "_maybe_update_core");    // 禁止 WordPress 检查更新
remove_action("admin_init", "_maybe_update_plugins"); // 禁止 WordPress 更新插件
remove_action("admin_init", "_maybe_update_themes");  // 禁止 WordPress 更新主题

function fake_update_callback(){
    return null;
}

2. URL防止危险代码

if (
    strpos($_SERVER["REQUEST_URI"], "eval(") || strpos($_SERVER["REQUEST_URI"], "base64") || strpos($_SERVER["REQUEST_URI"], "/**/")
) {
    @header("HTTP/1.1 414 Request-URI Too Long");
    @header("Status: 414 Request-URI Too Long");
    @header("Connection: Close");
    @exit;
}

3. 禁止多地同时登录

function pcl_user_has_concurrent_sessions(){
    return (is_user_logged_in() && count(wp_get_all_sessions()) > 2);
}

add_action("init", function () {
    // 除了管理员,其他人不允许多地同时登陆。
    if (!current_user_can("manage_options")) {
        if (!pcl_user_has_concurrent_sessions()) {
            return;
        }
        $newest = max(wp_list_pluck(wp_get_all_sessions(), "login"));
        $session = pcl_get_current_session();
        if ($session["login"] === $newest) {
            wp_destroy_other_sessions();
        } else {
            wp_destroy_current_session();
        }
    }
});

4. 禁用WordPress致命错误(WSOD)处理

define( "WP_DISABLE_FATAL_ERROR_HANDLER", true ); // wp-config.php
add_filter( "wp_fatal_error_handler_enabled", "__return_false" ); // functions.php

WordPress功能

1. 允许上传其它的文件类型

add_filter("upload_mimes", function ($mimes) use ($string) {
    $arr = explode(",", $string);
    foreach ($arr as $k) {
        $kv = explode("=", trim($k));
        if (count($kv) == 2) $mimes[trim($kv[0])] = trim($kv[1]);
    }
    return $mimes;
}, 99);

2. 禁用xmlrpc

add_filter("xmlrpc_enabled", "__return_false");
add_filter("xmlrpc_methods", function ($methods) {
    unset($methods["pingback.ping"]);
    return $methods;
});

3. 禁用Feed

function wpjam_feed_disabled(){
    wp_die("Feed已经关闭, 请访问网站首页!");
}

add_action("do_feed", "wpjam_feed_disabled", 1);
add_action("do_feed_rdf", "wpjam_feed_disabled", 1);
add_action("do_feed_rss", "wpjam_feed_disabled", 1);
add_action("do_feed_rss2", "wpjam_feed_disabled", 1);
add_action("do_feed_atom", "wpjam_feed_disabled", 1);

4. 禁用Rest API

add_filter("json_enabled", "__return_false");
add_filter("json_jsonp_enabled", "__return_false");
add_filter("rest_enabled", "__return_false");
add_filter("rest_jsonp_enabled", "__return_false");
remove_action("init", "rest_api_init");
remove_action("rest_api_init", "rest_api_default_filters", 10);
remove_action("parse_request", "rest_api_loaded");
remove_action("wp_head", "rest_output_link_wp_head", 10);
remove_action("template_redirect", "rest_output_link_header", 11);
remove_action("auth_cookie_malformed", "rest_cookie_collect_status");
remove_action("auth_cookie_expired", "rest_cookie_collect_status");
remove_action("auth_cookie_bad_username", "rest_cookie_collect_status");
remove_action("auth_cookie_bad_hash", "rest_cookie_collect_status");
remove_action("auth_cookie_valid", "rest_cookie_collect_status");

add_filter("rest_authentication_errors", function () {
    return new WP_Error("rest_disabled", __("The REST API on this site has been disabled."), ["status" => rest_authorization_required_code()]);
});

5. 账号注销后重定向

//账号登出后,重定向到登录页面
function redirect_custom_login_page() {
    wp_redirect(site_url() . "/sign-in");
    exit();
}
add_action("wp_logout", "redirect_custom_login_page");

WordPress优化加速

1. Wordpress头像使用v2ex CDN加速

// 替换Gravatar为v2ex CDN 头像源
function mytheme_get_avatar( $avatar ) {
    $avatar = preg_replace("/https:\/\/(secure|\d).gravatar.com\/avatar\//","https://cdn.v2ex.com/gravatar/",$avatar);
    return $avatar;
}
add_filter("get_avatar", "mytheme_get_avatar");

2. 移除wp_head不常用代码

remove_action("wp_head", "wp_generator");
foreach (["rss2_head", "commentsrss2_head", "rss_head", "rdf_header", "atom_head", "comments_atom_head", "opml_head", "app_head"] as $action) {
    remove_action($action, "the_generator");  //删除 head 中的 WP 版本号
}
remove_action("wp_head", "rsd_link");                        //删除 head 中的 RSD LINK
remove_action("wp_head", "wlwmanifest_link");                //删除 head 中的 Windows Live Writer 的适配器?

remove_action("wp_head", "feed_links_extra", 3);            //删除 head 中的 Feed 相关的link

remove_action("wp_head", "index_rel_link");                //删除 head 中首页,上级,开始,相连的日志链接
remove_action("wp_head", "parent_post_rel_link", 10);
remove_action("wp_head", "start_post_rel_link", 10);
remove_action("wp_head", "adjacent_posts_rel_link_wp_head", 10);

remove_action("wp_head", "wp_shortlink_wp_head", 10, 0);    //删除 head 中的 shortlink
remove_action("wp_head", "rest_output_link_wp_head", 10);    // 删除头部输出 WP RSET API 地址

remove_action("template_redirect", "wp_shortlink_header", 11);        //禁止短链接 Header 标签。
remove_action("template_redirect", "rest_output_link_header", 11);    // 禁止输出 Header Link 标签。

WordPress美化

1. 隐藏后台菜单

$list = ["upload.php"]; // 隐藏媒体库
add_action("admin_menu", function () use ($list) {
    foreach ($list as $v) {
        remove_menu_page($v);
    }
    global $menu;
    foreach ($menu as $v) {
        if ($v[4] == "wp-menu-separator") {
            unset($menu[4]);
        }
    }
});

2. 设置后台右下角文本

add_filter("admin_footer_text", function () {
    return "由WP2创建";
});

3. 移除Wordpress默认登录页logo

add_filter("login_title", function ($a) {
    return str_replace("WordPress", home_url(), $a);
});
add_action("login_head", function () {
echo "
    
    ";
});

4. 屏蔽后台隐私

remove_action("user_request_action_confirmed", "_wp_privacy_account_request_confirmed");
remove_action("user_request_action_confirmed", "_wp_privacy_send_request_confirmation_notification", 12); // After request marked as completed.
remove_action("wp_privacy_personal_data_exporters", "wp_register_comment_personal_data_exporter");
remove_action("wp_privacy_personal_data_exporters", "wp_register_media_personal_data_exporter");
remove_action("wp_privacy_personal_data_exporters", "wp_register_user_personal_data_exporter", 1);
remove_action("wp_privacy_personal_data_erasers", "wp_register_comment_personal_data_eraser");
remove_action("init", "wp_schedule_delete_old_privacy_export_files");
remove_action("wp_privacy_delete_old_export_files", "wp_privacy_delete_old_export_files");

add_filter("schedule_event", function ($event) {
if ($event && in_array($event->hook, ["wp_privacy_delete_old_export_files"])) {
    return false;
}
return $event;
});