6个超级实用的WordPress奇技淫巧

1、防止自动压缩图片

WordPress 默认会在上传 jpg 图片时自动压缩。这有利于节省带宽,减少加载时间。假如你是个摄影爱好者,热衷于在博客上展现摄影作品的话,高质量的图片就尤其重要了,将以下代码添加到 functions.php 文件,快速禁用图片自动压缩。

add_filter('jpeg_quality', function($arg){return 100;});

2、为所有的链接添加 target=”_blank” 属性

为所有链接添加 target="_blank" 属性,可以参考芒果之前的文章《HTML 中的 base 标记简介》,当然将下面代码添加到 functions.php 文件,也可以实现这个小功能。

function autoblank($text) {
	$return = str_replace('<a', '<a target="_blank"', $text);
	return $return;
}
add_filter('the_content', 'autoblank');

3、阻止 WordPress 压缩 jpg 图片

编辑 functions.php 文件并添加以下代码:

add_filter('jpeg_quality', function($arg){return 100;});

4、无需插件实现 WordPress 翻页功能

在需要显示翻页的地方引用以下代码:

global $wp_query;
$total = $wp_query->max_num_pages;
// only bother with the rest if we have more than 1 page!
if ( $total > 1 )  {
     // get the current page
     if ( !$current_page = get_query_var('paged') )
          $current_page = 1;
     // structure of "format" depends on whether we're using pretty permalinks
     $format = empty( get_option('permalink_structure') ) ? '&page=%#%' : 'page/%#%/';
     echo paginate_links(array(
          'base' => get_pagenum_link(1) . '%_%',
          'format' => $format,
          'current' => $current_page,
          'total' => $total,
          'mid_size' => 4,
          'type' => 'list'
     ));
}

5、自动替换文章中的字符

比如你的博客名称换了,你希望老的文章里同样可以更换一些文案。使用以下代码可以轻松搞定,将其拷贝至functions.php 文件即可。

function replace_text_wps($text){
    $replace = array(
        // 'WORD TO REPLACE' => 'REPLACE WORD WITH THIS'
        'wordpress' => '<a href="#">wordpress</a>',
        'excerpt' => '<a href="#">excerpt</a>',
        'function' => '<a href="#">function</a>'
    );
    $text = str_replace(array_keys($replace), $replace, $text);
    return $text;
}

add_filter('the_content', 'replace_text_wps');
add_filter('the_excerpt', 'replace_text_wps');

6、移除评论中的链接

WordPress 默认会把带有链接的评论自动加上链接。这也给垃圾评论提供了滋生的土壤。

移除这些评论链接很简单,把以下代码贴到 functions.php 文件就可以了。

remove_filter('comment_text', 'make_clickable', 9);

原文来自http://levi.yii.so/archives/1674