WordPress 优化分享总结

一、去除wordpress头部冗余代码

添加到模版functions.php文件头:

//去除头部冗余代码
remove_action('wp_head', 'feed_links_extra', 3);
remove_action('wp_head', 'feed_links', 2);
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'); //清除前后文信息
remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
remove_action('wp_head', 'rel_canonical'); //本页链接
remove_action('wp_head', 'wp_generator'); //移除WordPress版本号
remove_action('wp_head', 'wp_shortlink_wp_head'); //本页短链接
remove_action( 'template_redirect','wp_shortlink_header', 11, 0);
add_filter('xmlrpc_enabled', '__return_false');
add_filter('embed_oembed_discover', '__return_false');
remove_action('wp_head', 'wp_oembed_add_discovery_links');
remove_action('wp_head', 'wp_oembed_add_host_js');
remove_filter('pre_oembed_result', 'wp_filter_pre_oembed_result', 10);
// 屏蔽 REST API
add_filter('rest_enabled', '__return_false');
add_filter('rest_jsonp_enabled', '__return_false');
// 移除头部 wp-json 标签和 HTTP header 中的 link
remove_action('wp_head', 'rest_output_link_wp_head', 10);
remove_action( 'template_redirect','rest_output_link_header', 11, 0 );//屏蔽WP自带API产生的头部信息
//清除wp_footer带入的embed.min.js
function git_deregister_embed_script() {
    wp_deregister_script('wp-embed');
}
add_action('wp_footer', 'git_deregister_embed_script');
 
add_action( 'wp_enqueue_scripts', 'mt_enqueue_scripts', 1 );
function mt_enqueue_scripts() {
  wp_deregister_script('jquery');
}

二、替换文章内链接

添加到模版functions.php文件中

网上教程基本上都是操作数据库替换域名,这样的操作对于“小白”来说有一定的风险。

function replace_text_wps($text){
$replace = array(
'http://baidu.com' => 'http://www.baidu.com',//旧域名=>新域名,可以添加多个,按照格式每行添加一个
'http://old_domain' => 'http://new_domain', 
    );
 $text = str_replace(array_keys($replace), $replace, $text);
return $text;
}
add_filter('the_content', 'replace_text_wps');
add_filter('the_excerpt', 'replace_text_wps');

三、禁止使用Gutenberg块编辑器并恢复到经典编辑器

添加到模版functions.php文件中:

/**
 * WordPress完美禁止使用Gutenberg块编辑器并恢复到经典编辑器 - 龙笑天下
 * https://www.ilxtx.com/how-to-disable-gutenberg-block-editor.html
 */
// WP >= 5.0 正式集成Gutenberg古腾堡编辑器
if ( version_compare( get_bloginfo('version'), '5.0', '>=' ) ) {
    add_filter('use_block_editor_for_post', '__return_false'); // 切换回之前的编辑器
    remove_action( 'wp_enqueue_scripts', 'wp_common_block_scripts_and_styles' ); // 禁止前端加载样式文件
}else{
    // 4.9.8 < WP < 5.0 插件形式集成Gutenberg古腾堡编辑器
    add_filter('gutenberg_can_edit_post_type', '__return_false');
}

其它优化

添加到模版functions.php文件中

//删除文章时删除图片附件
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');
 
 
//彻底禁止WordPress缩略图
add_filter( 'add_image_size', create_function( '', 'return 1;' ) );

//搜索结果只有一篇文章时跳转到该文章
add_action('template_redirect', 'redirect_single_post');
function redirect_single_post() {
if (is_search()) {
global $wp_query;
if ($wp_query->post_count == 1 && $wp_query->max_num_pages == 1) {
wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );
exit;
}
}
}

/**
 * WordPress 自动为文章添加已使用过的标签(文章内容版本)
 */
add_action('save_post', 'auto_add_tags');
function auto_add_tags(){
    $tags = get_tags( array('hide_empty' => false) );
    $post_id = get_the_ID();
    $post_content = get_post($post_id)->post_content;
    if ($tags) {
        foreach ( $tags as $tag ) {
            // 如果文章内容出现了已使用过的标签,自动添加这些标签
            if ( strpos($post_content, $tag->name) !== false)
                wp_set_post_tags( $post_id, $tag->name, true );
        }
    }
}
// 评论添加@符号
function wp_comment_add_at( $comment_text, $comment = '') {
if( $comment->comment_parent > 0) {
$comment_text = '@<a href="#comment-' . $comment->comment_parent . '">'.get_comment_author( $comment->comment_parent ) . '</a>: ' . $comment_text;
}
return $comment_text;
}
add_filter( 'comment_text' , 'wp_comment_add_at', 20, 2);

// 评论中需要有中文
function wp_refused_spam_comments($comment_data) {
$pattern = '/[一-龥]/u';
$jpattern = '/[ぁ-ん]+|[ァ-ヴ]+/u';
if (!preg_match($pattern, $comment_data['comment_content'])) {
err(__('评论中需要有一个汉字!'));
}
if (preg_match($jpattern, $comment_data['comment_content'])) {
err(__('不能有日文!'));
}
return ($comment_data);
}
add_filter('preprocess_comment', 'wp_refused_spam_comments');

//禁止加载默认jq库
function my_enqueue_scripts() {
wp_deregister_script('jquery');
}
add_action( 'wp_enqueue_scripts', 'my_enqueue_scripts', 1 );

// 删掉自动草稿和修订版
$wpdb->query("DELETE FROM `$wpdb->posts` WHERE `post_status` = 'auto-draft' OR `post_type` = 'revision'");

//去除分类标志代码
add_action( 'load-themes.php',  'no_category_base_refresh_rules');
add_action('created_category', 'no_category_base_refresh_rules');
add_action('edited_category', 'no_category_base_refresh_rules');
add_action('delete_category', 'no_category_base_refresh_rules');
function no_category_base_refresh_rules() {
    global $wp_rewrite;
    $wp_rewrite -> flush_rules();
}
// register_deactivation_hook(__FILE__, 'no_category_base_deactivate');
// function no_category_base_deactivate() {
//  remove_filter('category_rewrite_rules', 'no_category_base_rewrite_rules');
//  // We don't want to insert our custom rules again
//  no_category_base_refresh_rules();
// }
// Remove category base
add_action('init', 'no_category_base_permastruct');
function no_category_base_permastruct() {
    global $wp_rewrite, $wp_version;
    if (version_compare($wp_version, '3.4', '<')) {
        // For pre-3.4 support
        $wp_rewrite -> extra_permastructs['category'][0] = '%category%';
    } else {
        $wp_rewrite -> extra_permastructs['category']['struct'] = '%category%';
    }
}
 
// Add our custom category rewrite rules
add_filter('category_rewrite_rules', 'no_category_base_rewrite_rules');
function no_category_base_rewrite_rules($category_rewrite) {
    //var_dump($category_rewrite); // For Debugging
    $category_rewrite = array();
    $categories = get_categories(array('hide_empty' => false));
    foreach ($categories as $category) {
        $category_nicename = $category -> slug;
        if ($category -> parent == $category -> cat_ID)// recursive recursion
            $category -> parent = 0;
        elseif ($category -> parent != 0)
            $category_nicename = get_category_parents($category -> parent, false, '/', true) . $category_nicename;
        $category_rewrite['(' . $category_nicename . ')/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?category_name=$matches[1]&feed=$matches[2]';
        $category_rewrite['(' . $category_nicename . ')/page/?([0-9]{1,})/?$'] = 'index.php?category_name=$matches[1]&paged=$matches[2]';
        $category_rewrite['(' . $category_nicename . ')/?$'] = 'index.php?category_name=$matches[1]';
    }
    // Redirect support from Old Category Base
    global $wp_rewrite;
    $old_category_base = get_option('category_base') ? get_option('category_base') : 'category';
    $old_category_base = trim($old_category_base, '/');
    $category_rewrite[$old_category_base . '/(.*)$'] = 'index.php?category_redirect=$matches[1]';
    //var_dump($category_rewrite); // For Debugging
    return $category_rewrite;
}
// Add 'category_redirect' query variable
add_filter('query_vars', 'no_category_base_query_vars');
function no_category_base_query_vars($public_query_vars) {
    $public_query_vars[] = 'category_redirect';
    return $public_query_vars;
}
// Redirect if 'category_redirect' is set
add_filter('request', 'no_category_base_request');
function no_category_base_request($query_vars) {
    //print_r($query_vars); // For Debugging
    if (isset($query_vars['category_redirect'])) {
        $catlink = trailingslashit(get_option('home')) . user_trailingslashit($query_vars['category_redirect'], 'category');
        status_header(301);
        header("Location: $catlink");
        exit();
    }
    return $query_vars;
}