wordpress6.2 优化日志

wordpress英文版6.2,twenty-twenty three。有些优化手段个人感觉没有必要,或条件限制暂时没有做,标记为“未做”。经过这个过程认为核心程序没有优化的必要,在具体部署的时候才有优化的需求。尤其是各插件、主题,需要优化,有些占内存,有些占CPU。

第一步:WordPress数据库优化

1、禁止WordPress自动保存文章草稿、文章修订

remove_filter('the_content', 'wptexturize');
remove_action('pre_post_update', 'wp_save_post_revision' );
add_action( 'wp_print_scripts', 'disable_autosave' );
function disable_autosave() {
    wp_deregister_script('autosave');
}

2、删除冗余数据( 未做)

<?php
//wordpress数据库优化脚本 by v7v3.com
$hostname_blog = "localhost";//设定数据库主机,同wp-config.php
$database_blog = "wordpress";//设定数据库名,同wp-config.php
$username_blog = "root";//设定数据库用户名,同wp-config.php
$password_blog = "";//设定数据库密码,同wp-config.php
$blog = mysql_pconnect($hostname_blog, $username_blog, $password_blog) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_blog, $blog);
mysql_query('DELETE FROM wp_posts WHERE post_type = "revision"');
mysql_query('DELETE FROM wp_postmeta WHERE meta_key = "_edit_lock"');
mysql_query('DELETE FROM wp_postmeta WHERE meta_key = "_edit_last"');
mysql_query('DELETE FROM wp_commentmeta WHERE meta_key LIKE "%trash%"');
mysql_query('DELETE FROM wp_comments WHERE comment_approved = "trash"');
mysql_query('DELETE FROM wp_options WHERE option_name REGEXP "_transient_"');
mysql_query('DELETE FROM wp_postmeta WHERE meta_key = ‘_wp_attached_file’');
mysql_query('DELETE FROM wp_postmeta WHERE meta_key = ‘_wp_attachment_metadata’');
mysql_query("delete from wp_posts
where (post_status='auto-draft' or post_status='inherit')
and post_type='post'");
$tablelist = mysql_query("SHOW TABLES");
while($checklist = mysql_fetch_array($tablelist)) {
       $optimization=mysql_query("OPTIMIZE TABLE `$checklist[0]`");
}
echo 'Done';

//ps记得修改数据库前缀~
//使用时将脚本上传至网站任意目录后并且通过浏览器访问即可一键优化wordprsss数据库。

3、屏蔽垃圾评论提交到数据库(没有操作)

function robin_fuckspam($comment) {
    if(  is_user_logged_in()){ return $comment;} //登录用户无压力...
    if( wp_blacklist_check($comment['comment_author'],$comment['comment_author_email'],$comment['comment_author_url'],$comment['comment_content'], $comment['comment_author_IP'], $comment['comment_agent'] )){
        header("Content-type: text/html; charset=utf-8");
        wp_die('
您评论包含辱骂,过激或者违反法律等言论,或者您的IP已被加入黑名单,如有疑问请联系管理员处理!<a href="javascript:history.go(-1);">返回文章页</a>
');
    }  else  {
        return $comment;
    }
}
add_filter('preprocess_comment', 'robin_fuckspam');

4、修改WordPress自动保存间隔,到wp-config.php更改

define( 'AUTOSAVE_INTERVAL', 120 );

这会将自动保存频率设置为2分钟一次,而不是默认的1秒一次。

5、降低心跳检测API频率

WordPress采用了心跳检测的方式,每隔60秒向服务器发送一次请求。心跳检测有多种用途,比如获取是否有其他用户也在使用后台编辑内容,并实时通知对方,防止内容发生冲突。如果有多个用户同时在后台作业时就会导致服务器压力过大。

可以使用heartbeat-control插件进行心跳频率更改,建议改为至少120秒。

禁用
add_action( 'init', 'stop_heartbeat', 1 );
function stop_heartbeat() {
    wp_deregister_script('heartbeat');
}


更改时长
add_filter( 'heartbeat_settings', 'custom_heartbeat_settings' );
function custom_heartbeat_settings( $settings ) {
    $settings['interval'] = 60; // 设置心跳频率为60秒
    return $settings;
}

6、将Wordpress的Gravatar头像图片缓存到本地

要想将Wordpress的Gravatar头像图片缓存到本地,先在网站的根目录新建一个avatar 的文件夹,读写权限设置为755

function my_avatar($avatar) {
    $tmp = strpos($avatar, 'http');
    $g = substr($avatar, $tmp, strpos($avatar, "'", $tmp) - $tmp);
    $tmp = strpos($g, 'avatar/') + 7;
    $f = substr($g, $tmp, strpos($g, "?", $tmp) - $tmp);
    $w = get_bloginfo('wpurl');
    $e = ABSPATH .'avatar/'. $f .'.jpg';
    $t = 1209600; //14天刷新一次缓存, 单位:秒
    if ( !is_file($e) || (time() - filemtime($e)) > $t ) { //當頭像不存在或文件超過14天才更新
        copy(htmlspecialchars_decode($g), $e);
    } else {$avatar = strtr($avatar, array($g => $w.'/avatar/'.$f.'.jpg'));
    if (filesize($e) < 500) copy($w.'/avatar/default.jpg', $e);
    return $avatar;}
}
add_filter('get_avatar', 'my_avatar');

7、将Gravatar头像缓存到多说或七牛国内镜像服务器实现加速

function mytheme_get_avatar($avatar) {
$avatar = str_replace(array("www.gravatar.com","0.gravatar.com","1.gravatar.com","2.gravatar.com"),
"dadu2.qiniudn.com",$avatar);
return $avatar;
}

add_filter( 'get_avatar', 'mytheme_get_avatar', 10, 3 );

8、在后台关闭头像,或自定义头像

9、替换Gravatar头像为Cravatar头像

if ( ! function_exists( 'get_cravatar_url' ) ) {
/**
*替换Gravatar头像为Cravatar头像
*
* Cravatar是Gravatar在中国的完美替代方案,你可以在https://cravatar.cn更新你的头像
*/
function get_cravatar_url( $url ) {
$sources = array(
'www.gravatar.com',
'0.gravatar.com',
'1.gravatar.com',
'2.gravatar.com',
'secure.gravatar.com',
'cn.gravatar.com'
);
return str_replace( $sources, 'cravatar.cn', $url );
}
add_filter( 'um_user_avatar_url_filter', 'get_cravatar_url', 1 );
add_filter( 'bp_gravatar_url', 'get_cravatar_url', 1 );
add_filter( 'get_avatar_url', 'get_cravatar_url', 1 );
}
if ( ! function_exists( 'set_defaults_for_cravatar' ) ) {
/**
*替换WordPress讨论设置中的默认头像
*/
function set_defaults_for_cravatar( $avatar_defaults ) {
$avatar_defaults['gravatar_default']='Cravatar标志';
return $avatar_defaults;
}
add_filter( 'avatar_defaults', 'set_defaults_for_cravatar', 1 );
}

9、SSL的头像没有被墙?

function get_ssl_avatar($avatar) {
   $avatar = preg_replace('/.*\/avatar\/(.*)\?s=([\d]+)&.*/','<img src="https://secure.gravatar.com/avatar/$1?s=$2" class="avatar avatar-$2" height="$2" width="$2">',$avatar);
   return $avatar;
}
add_filter('get_avatar', 'get_ssl_avatar');

10、修改内存限制

define( 'WP_MEMORY_LIMIT', '512M' );

14、部分选用

<!--添加优化代码到主题目录functions.php文件-->

/*彻底关闭自动更新(核心程序/主题/插件/翻译自动更新*/
add_filter('automatic_updater_disabled', '__return_true');

/*关闭更新检查定时作业*/
remove_action('init', 'wp_schedule_update_checks');

/*移除已有的版本检查定时作业*/
wp_clear_scheduled_hook('wp_version_check');

/*移除已有的插件更新定时作业*/
wp_clear_scheduled_hook('wp_update_plugins');

/*移除已有的主题更新定时作业*/
wp_clear_scheduled_hook('wp_update_themes');

/*移除已有的自动更新定时作业*/
wp_clear_scheduled_hook('wp_maybe_auto_update');

/*移除后台内核更新检查*/
remove_action( 'admin_init', '_maybe_update_core' );

/*移除后台插件更新检查*/
remove_action( 'load-plugins.php', 'wp_update_plugins' );
remove_action( 'load-update.php', 'wp_update_plugins' );
remove_action( 'load-update-core.php', 'wp_update_plugins' );
remove_action( 'admin_init', '_maybe_update_plugins' );

/*移除后台主题更新检查*/
remove_action( 'load-themes.php', 'wp_update_themes' );
remove_action( 'load-update.php', 'wp_update_themes' );
remove_action( 'load-update-core.php', 'wp_update_themes' );
remove_action( 'admin_init', '_maybe_update_themes' );

/*关闭程序更新提示*/
add_filter( 'pre_site_transient_update_core', function($a){ return null; });

/*关闭插件更新提示*/
add_filter('pre_site_transient_update_plugins', function($a){return null;});

/*关闭主题更新提示*/
add_filter('pre_site_transient_update_themes', function($a){return null;});

//关闭WordPress的XML-RPC功能
add_filter('xmlrpc_enabled', '__return_false');

/* 关闭XML-RPC的pingback端口 */
add_filter( 'xmlrpc_methods', 'remove_xmlrpc_pingback_ping' );
function remove_xmlrpc_pingback_ping( $methods ) {
unset( $methods['pingback.ping'] );
return $methods;
}

//禁用 pingbacks, enclosures, trackbacks
remove_action( 'do_pings', 'do_all_pings', 10 );

//去掉 _encloseme 和 do_ping 操作
remove_action( 'publish_post','_publish_post_hook',5 );

/* 禁止加载s.w.org获取表情和头像 */
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');
function remove_dns_prefetch( $hints, $relation_type ) {
    if ( 'dns-prefetch' === $relation_type ) {
        return array_diff( wp_dependencies_unique_hosts(), $hints );
    }
    return $hints;
}
add_filter( 'wp_resource_hints', 'remove_dns_prefetch', 10, 2 );

/* 完全禁止REST API、移除wp-json链接 */
function lerm_disable_rest_api( $access ) {
return new WP_Error(
  'Stop!',
  'Soooooryyyy',
  array(
   'status' => 403,
  )
);
}
add_filter( 'rest_authentication_errors', 'lerm_disable_rest_api' );
remove_action( 'wp_head', 'rest_output_link_wp_head', 10 );

/* 禁止查询网站静态资源连接版本字符 */
function _remove_script_version ( $src ){
  $parts = explode( '?', $src );
  return $parts[0];
}
add_filter( 'script_loader_src', '_remove_script_version', 15, 1 );
add_filter( 'style_loader_src', '_remove_script_version', 15, 1 );

/* 移除前端网页源代码内的头部冗余代码 */
remove_action( 'wp_head', 'feed_links_extra', 3 );
remove_action( 'wp_head', 'rsd_link' );
remove_action( 'wp_head', 'wlwmanifest_link' );
remove_action( 'wp_head', 'index_rel_link' );
remove_action( 'wp_head', 'start_post_rel_link', 10, 0 );
remove_action( 'wp_head', 'wp_generator' );

/* 禁止新版文章编辑器加载前端样式 */
function wpassist_remove_block_library_css(){
wp_dequeue_style( 'wp-block-library' );
}
remove_action( 'wp_enqueue_scripts', 'wp_common_block_scripts_and_styles' );
add_action( 'wp_enqueue_scripts', 'wpassist_remove_block_library_css' );

/* 移除新版本站点健康状态面板和菜单项 */
add_action( 'admin_menu', 'remove_site_health_menu' );
function remove_site_health_menu(){
remove_submenu_page( 'tools.php','site-health.php' );
}

/* 禁用5.5版后自带的XML站点地图 */
add_filter( 'wp_sitemaps_enabled', '__return_false' );

/* 移除前后台顶部工具栏指定菜单 */
function admin_bar_item ( WP_Admin_Bar $admin_bar ) {
$admin_bar->remove_menu('wp-logo'); //移动wp的logo
$admin_bar->remove_menu('site-name'); //移动站点名称
$admin_bar->remove_menu('updates'); //移动更新提示
$admin_bar->remove_menu('comments'); //移动评论提示
/*$admin_bar->remove_menu('new-content'); //移除新建按钮  */
}
add_action( 'admin_bar_menu', 'admin_bar_item', 500 );

//移除后台仪表盘站点健康状态面板
add_action('wp_dashboard_setup', 'remove_site_health_dashboard_widget');
function remove_site_health_dashboard_widget()
{
remove_meta_box('dashboard_site_health', 'dashboard', 'normal');
}

//移除后台仪表盘菜单:站点健康状态
add_action( 'admin_menu', 'remove_site_health_menu' );
function remove_site_health_menu(){
remove_submenu_page( 'tools.php','site-health.php' );
}

//移除后台仪表盘菜单:活动、新闻
function bzg_remove_dashboard_widgets() {
global $wp_meta_boxes;

#移除 "活动"
unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_activity']);

#移除 "WordPress 新闻"
unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_primary']);
}
add_action('wp_dashboard_setup', 'bzg_remove_dashboard_widgets' );

//移除后台仪表盘菜单:帮助
function bzg_remove_help() {
get_current_screen()->remove_help_tabs();
}
add_action('admin_head', 'bzg_remove_help');

//移除后台页面title标题的wordpress后缀
add_filter('admin_title', 'delAdminTitle', 10, 2);
function delAdminTitle($admin_title, $title){
return $title.' ‹ '.get_bloginfo('name');
}

//移除登陆页面title标题的wordpress后缀
add_filter('login_title', 'remove_login_title', 10, 2);
function remove_login_title($login_title, $title){
return $title.' ‹ '.get_bloginfo('name');
}

/* 彻底禁止4.4+版之后响应式图片功能及缩略图裁剪功能*/

// 禁止生成图像尺寸
function zm_customize_image_sizes( $sizes ){
unset( $sizes[ 'thumbnail' ]);
unset( $sizes[ 'medium' ]);
unset( $sizes[ 'medium_large' ] );
unset( $sizes[ 'large' ]);
unset( $sizes[ 'full' ] );
unset( $sizes['1536x1536'] );
unset( $sizes['2048x2048'] );
return $sizes;
}
add_filter( 'intermediate_image_sizes_advanced', 'zm_customize_image_sizes' );

// 禁止缩放图片尺寸
add_filter('big_image_size_threshold', '__return_false');

// 禁止生成其它图像尺寸
function shapeSpace_disable_other_image_sizes() {
    // 禁止通过set_post_thumbnail_size()函数生成的图片尺寸
    remove_image_size('post-thumbnail');

    // 禁止添加其它图像尺寸
    remove_image_size('another-size');
}
add_action('init', 'shapeSpace_disable_other_image_sizes');

//切换经典文章编辑器(v5.x开始默认古腾堡编辑器)
add_filter('use_block_editor_for_post', '__return_false');

//替换评论用户头像链接为国内镜像加速访问
add_filter('get_avatar', function ($avatar) {
return str_replace([
'www.gravatar.com/avatar/',
'0.gravatar.com/avatar/',
'1.gravatar.com/avatar/',
'2.gravatar.com/avatar/',
'secure.gravatar.com/avatar/',
'cn.gravatar.com/avatar/'
], 'cravatar.cn/', $avatar);
});

//取消内容转义
remove_filter('the_content', 'wptexturize');

//取消摘要转义
remove_filter('the_excerpt', 'wptexturize');

//取消评论转义
remove_filter('comment_text', 'wptexturize');

//禁止转义引号字符
remove_filter('the_content', 'wptexturize'); // 禁止英文引号转义为中文引号

//文章插入图片自动移除 img 的 width、height、class 属性;
add_filter( 'post_thumbnail_html', 'fanly_remove_images_attribute', 10 );
add_filter( 'image_send_to_editor', 'fanly_remove_images_attribute', 10 );
function fanly_remove_images_attribute( $html ) {
//$html = preg_replace( '/(width|height)="\d*"\s/', "", $html );
$html = preg_replace( '/width="(\d*)"\s+height="(\d*)"\s+class="[^"]*"/', "", $html );
$html = preg_replace( '/  /', "", $html );
return $html;
}

// 自适应图片删除width和height
function ludou_remove_width_height_attribute($content){
  preg_match_all('/<[img|IMG].*?src=[\'|"](.*?(?:[\.gif|\.jpg|\.png\.webp]))[\'|"].*?[\/]?>/', $content, $images);
  if(!empty($images)) {
foreach($images[0] as $index => $value){
   $new_img = preg_replace('/(width|height)="\d*"\s/', "", $images[0][$index]);
   $content = str_replace($images[0][$index], $new_img, $content);
}
  }
  return $content;
}

//判断是否是移动设备浏览
if(wp_is_mobile()) {
  #删除文章内容中img的width和height属性
  add_filter('the_content', 'ludou_remove_width_height_attribute', 99);
}

/* 删除文章时删除图片附件 */
function delete_post_and_attachments($post_ID) {
global $wpdb;

#删除特色图片
$thumbnails = $wpdb->get_results( "SELECT * FROM $wpdb->postmeta WHERE meta_key = '_thumbnail_id' AND post_id = $post_ID" );
foreach ( $thumbnails as $thumbnail ) {
wp_delete_attachment( $thumbnail->meta_value, true );
}

#删除图片附件
$attachments = $wpdb->get_results( "SELECT * FROM $wpdb->posts WHERE post_parent = $post_ID AND post_type = 'attachment'" );
foreach ( $attachments as $attachment ) {
wp_delete_attachment( $attachment->ID, true );
}

$wpdb->query( "DELETE FROM $wpdb->postmeta WHERE meta_key = '_thumbnail_id' AND post_id = $post_ID" );

}

add_action('before_delete_post', 'delete_post_and_attachments');

第二步:前端优化

1、CDN加速(未做):

2、去除冗余的html代码 (未做):

remove_action( 'wp_head', 'wp_enqueue_scripts', 1 ); //Javascript的调用
remove_action( 'wp_head', 'feed_links', 2 ); //移除feed
remove_action( 'wp_head', 'feed_links_extra', 3 ); //移除feed
remove_action( 'wp_head', 'rsd_link' ); //移除离线编辑器开放接口
remove_action( 'wp_head', 'wlwmanifest_link' );  //移除离线编辑器开放接口
remove_action( 'wp_head', 'index_rel_link' );//去除本页唯一链接信息
remove_action('wp_head', 'parent_post_rel_link', 10, 0 );//清除前后文信息
remove_action('wp_head', 'start_post_rel_link', 10, 0 );//清除前后文信息
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0 );
remove_action( 'wp_head', 'locale_stylesheet' );
remove_action('publish_future_post','check_and_publish_future_post',10, 1 );
remove_action( 'wp_head', 'noindex', 1 );
remove_action( 'wp_head', 'wp_print_styles', 8 );//载入css
remove_action( 'wp_head', 'wp_print_head_scripts', 9 );
remove_action( 'wp_head', 'wp_generator' ); //移除WordPress版本
remove_action( 'wp_head', 'rel_canonical' );
remove_action( 'wp_footer', 'wp_print_footer_scripts' );
remove_action( 'wp_head', 'wp_shortlink_wp_head', 10, 0 );
remove_action( 'template_redirect', 'wp_shortlink_header', 11, 0 );
add_action('widgets_init', 'my_remove_recent_comments_style');
function my_remove_recent_comments_style() {
global $wp_widget_factory;
remove_action('wp_head', array($wp_widget_factory->widgets['WP_Widget_Recent_Comments'] ,'recent_comments_style'));
}

3、安装Local Google Fonts插件 ,实现google 字体本地化

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值