WordPress優(yōu)化網(wǎng)站的8個(gè)有用的代碼片段
WordPress優(yōu)化網(wǎng)站的8個(gè)有用的代碼片段都是用來優(yōu)化wordpress的,不少是添加到wp-config.php 文件的。
1、自動(dòng)清空文章“回收站”時(shí)間間隔
默認(rèn)的話,WordPress 對(duì)于刪除到“回收站”的文章是每隔30 天予以清空(原文如此說,貌似沒有吧?),如果你嫌時(shí)間過長,可以通過wp-config.php 自定義設(shè)置,如下面的代碼設(shè)置刪除間隔為 7天:
define ('EMPTY_TRASH_DAYS', 7);
或者直接不用經(jīng)過回收站,一次性刪除干凈:
define ('EMPTY_TRASH_DAYS', 0);
2、減少文章歷史版本
忘記從哪個(gè)版本開始的“WordPress 版本控制”功能對(duì)許多用戶來說就是累贅,每隔一段時(shí)間就自動(dòng)保存文章草稿,看似便捷下無形中為數(shù)據(jù)庫添加了許多亢余數(shù)據(jù)。通過在wp-config.php 添加下面的代碼,你可以減少自動(dòng)保存次數(shù):
define( 'WP_POST_REVISIONS', 3 );
甚至,你可以禁止這個(gè)功能:
define( 'WP_POST_REVISIONS', false );
3、移動(dòng) WP-Content 文件夾
WordPress 的WP-Content 文件夾專門是提供上傳文件夾、主題文件、插件文件等,也因?yàn)檫@個(gè)原因,常常會(huì)成為黑客覬覦的對(duì)象。通過下面的代碼,你可以將WP-Content 文件夾移動(dòng)到其他地方(在wp-config.php 寫入):
define( 'WP_CONTENT_DIR', dirname(__FILE__) . '/newlocation/wp-content' );
或者:
define( 'WP_CONTENT_URL', 'http://www.yourwebsite.com/newlocation/wp-content' );
甚至,你可以重命名這個(gè)WP-Content 文件夾名,WordPress 中已經(jīng)提供了這個(gè)函數(shù),你需要這么做:
define ('WP_CONTENT_FOLDERNAME', 'newfoldername');
4、將“作者文章列表”鏈接跳轉(zhuǎn)到about 頁面,代碼如下:
add_filter( 'author_link', 'my_author_link' );
function my_author_link() {
return home_url( 'about' );
}
5、搜索結(jié)果只有一篇文章時(shí)自動(dòng)跳轉(zhuǎn)到文章,代碼如下:
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;
}
}
}
6、搜索結(jié)果中排除頁面的搜索結(jié)果
function filter_search($query) {
if ($query->is_search) {
$query->set('post_type', 'post');
}
return $query;
}
add_filter('pre_get_posts', 'filter_search');
7、移除評(píng)論表單中的url 域
這個(gè)是為了防范垃圾評(píng)論,你懂的。
function remove_comment_fields($fields) {
unset($fields['url']);
return $fields;
}
add_filter('comment_form_default_fields','remove_comment_fields');
8、強(qiáng)制最少評(píng)論文字字?jǐn)?shù)
這個(gè)是為了防范垃圾評(píng)論+灌水評(píng)論,你懂的。
add_filter( 'preprocess_comment', 'minimal_comment_length' );
function minimal_comment_length( $commentdata ) {
$minimalCommentLength = 20;
if ( strlen( trim( $commentdata['comment_content'] ) ) < $minimalCommentLength ){
wp_die( 'All comments must be at least ' . $minimalCommentLength . ' characters long.' );
}
return $commentdata;
}