WordPress 中八个有用的代码片段

WordPress 中八个有用的代码片段

看到Elegantthemes 上的这篇文章不错,索性半翻译半修改过来。这里介绍了WordPress 中八个有用的代码片段,都是用来优化WordPress 的,不少是添加到wp-config.php 文件的。

1、自动清空文章“回收站”时间间隔

默认的话,WordPress 对于删除到“回收站”的文章是每隔30 天予以清空(原文如此说,貌似没有吧?),如果你嫌时间过长,可以通过wp-config.php 自定义设置,如下面的代码设置删除间隔为 7天:

define ('EMPTY_TRASH_DAYS', 7);

或者直接不用经过回收站,一次性删除干净:

define ('EMPTY_TRASH_DAYS', 0);

2、减少文章历史版本

忘记从哪个版本开始的“WordPress 版本控制”功能对许多用户来说就是累赘,每隔一段时间就自动保存文章草稿,看似便捷下无形中为数据库添加了许多亢余数据。通过在wp-config.php 添加下面的代码,你可以减少自动保存次数:

define( 'WP_POST_REVISIONS', 3 );

甚至,你可以禁止这个功能:

define( 'WP_POST_REVISIONS', false );

3、移动 WP-Content 文件夹

WordPress 的WP-Content 文件夹专门是提供上传文件夹、主题文件、插件文件等,也因为这个原因,常常会成为黑客觊觎的对象。通过下面的代码,你可以将WP-Content 文件夹移动到其他地方(在wp-config.php 写入):

define( 'WP_CONTENT_DIR', dirname(__FILE__) . '/newlocation/wp-content' );

或者:

define( 'WP_CONTENT_URL', 'http://www.yourwebsite.com/newlocation/wp-content' );

甚至,你可以重命名这个WP-Content 文件夹名,WordPress 中已经提供了这个函数,你需要这么做:

define ('WP_CONTENT_FOLDERNAME', 'newfoldername');

4、将“作者文章列表”链接跳转到about 页面

详细解释见《WordPress重定向作者归档链接到“关于”页面》,代码如下:

add_filter( 'author_link', 'my_author_link' );
 
function my_author_link() {
    return home_url( 'about' );
}

5、搜索结果只有一篇文章时自动跳转到文章

详细解释见《 WordPress内置搜索结果只有一篇文章时自动跳转到文章,代码如下:

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、搜索结果中排除页面的搜索结果

function filter_search($query) {
    if ($query->is_search) {
        $query->set('post_type', 'post');
    }
    return $query;
}
add_filter('pre_get_posts', 'filter_search');

7、移除评论表单中的url 域

这个是为了防范垃圾评论,你懂的。

function remove_comment_fields($fields) {
    unset($fields['url']);
    return $fields;
}
add_filter('comment_form_default_fields','remove_comment_fields');

8、强制最少评论文字字数

这个是为了防范垃圾评论+灌水评论,你懂的。

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;
}
评分:
当前平均分 0.00 (0%) - 0 个投票
6 条 评论
  1. 不错的内容,赞+

    9年前 回复
  2. 最后一个好用

    9年前 回复
  3. Mark收藏

    10年前 回复
  4. 这个好,收藏起来!

    10年前 回复
  5. 看着还是挺有用的!

    10年前 回复
  6. 实用,学习了

    10年前 回复
发表评论