整理:WordPress常用代码片段

在使用WordPress中,我不喜欢装太多插件让网站太臃肿,能用代码实现的我喜欢用代码实现,所以今天我整理了一些WordPress开发中常用的代码片段,将代码放入functions.php中就能使用,便于大家查阅,后续将持续更新。

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 ymk_feed_disabled()
{
    wp_die("Feed已经关闭, 请访问网站<a href="" . get_bloginfo("url") . "">首页</a>!");
}
 
add_action("do_feed", "ymk_feed_disabled", 1);
add_action("do_feed_rdf", "ymk_feed_disabled", 1);
add_action("do_feed_rss", "ymk_feed_disabled", 1);
add_action("do_feed_rss2", "ymk_feed_disabled", 1);
add_action("do_feed_atom", "ymk_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 "由云码库创建";
});

3. 移除Wordpress默认登录页logo

add_filter("login_title", function ($a) {
    return str_replace("WordPress", home_url(), $a);
});
add_action("login_head", function () {
    echo "
        <style type="text/css">
        #login {width: 392px;}
        #login h1 a {display: none !important;}
        #backtoblog,#nav {display: none}
        .login {
            background: #21607d;
        }
        input[type=text],input[type=password] {
         border-color: #c3e3ff;
        }
        .login form .input, .login input[type=password], .login input[type=text] {
            border-radius: 0;
        }
        </style>
        ";
});

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;
});

 

1. 本站所有资源均来源于用户上传和网络,如有侵权请联系站长!
2. 分享目的仅供大家学习和交流,请在下载后24小时内删除!
3. 不得用于商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,均不包含技术服务请知悉!
5. 本站资源售价只是赞助,赞助费用仅维持本站的日常运营所需!
云码库 » 整理:WordPress常用代码片段

发表评论

提供最优质的资源集合

立即查看 了解详情