WordPress开发中常用代码(必备)

        很多人在WordPress开发中常用代码,WordPress 相比其它网站程序,最突出的优势:主题模板多,插件多,相关技术文章多,只要你想到的功能,都可以通过插件或者代码实现。现在分享下WordPress常用代码,将代码放入执行文件(例如:functions.php)中就即可,便于大家查阅,不断更新中...

WordPress开发中常用代码(必备)_第1张图片 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;
});

//果你还是用使用第三方客户端来管理 WordPress 文章,那么可以只关闭 XML-RPC 的 pingback 端口
//禁用XML-RPC的pingback接口
add_filter( 'xmlrpc_methods', 'remove_xmlrpc_pingback_ping' );
function remove_xmlrpc_pingback_ping( $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 "创建者XXX";
});

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

5.禁用 WordPress 卡片嵌入式内链 Post Embed 功能

在当前主题的 functions.php 文件中添加如下代码来屏蔽 Post Embed 该功能:

remove_action('rest_api_init', 'wp_oembed_register_route');
remove_filter('rest_pre_serve_request', '_oembed_rest_pre_serve_request', 10, 4);
 
remove_filter('oembed_dataparse', 'wp_filter_oembed_result', 10 );
remove_filter('oembed_response_data', 'get_oembed_response_data_rich', 10, 4);
 
remove_action('wp_head', 'wp_oembed_add_discovery_links');
remove_action('wp_head', 'wp_oembed_add_host_js');

        有一个叫 Disable Embeds 的插件是专门用来禁用文件嵌入功能的,在后台搜索安装启用,实现的效果和上面介绍的代码是一样的。

你可能感兴趣的:(WordPress,wordpress,wordpress实用代码,WordPress加速优化,WordPress功能,WordPress代码)