使 WordPress 的搜索结果包含加密或私密文章

   Updated: 2013-12-01 16:38       使 WordPress 的搜索结果包含加密或私密文章有 2 条评论

目前新版本的 WordPress(我此刻使用的是 v3.3.1),如果未登录,在搜索结果中是不包含加密文章的。根据网上查找的资料看,某个版本以前的 WordPress 搜索结果是包含加密文章的,后来某个版本之后,这个功能就去掉了,可能是基于隐私策略的考虑。

但我个人有不同的理解:

  • Private 就是私人的意思,所以 Private 的文章仅限于作者,只有作者才能查看和搜索。
  • Password protected 的文章仅仅是密码保护,应该让游客搜索到,任何人只要知道这篇文章的密码就可以查看,否则这个密码就失去它的意义了(Password protected 的文章作者查看也是需要输入密码的)。

网上找了很久无果,今天尝试用英文搜索,终于在一个国外的 Blog 站点找到解决办法。

编辑当前主题下的 functions.php 文件,在<?php 与 ?> 中间添加代码即可。

使未登录用户的搜索结果包含加密文章的代码

add_filter( 'posts_search', 'include_password_posts_in_search' );
function include_password_posts_in_search( $search ) {
    global $wpdb;
    if( !is_user_logged_in() ) {
        $pattern = " AND ({$wpdb->prefix}posts.post_password = '')";
        $search = str_replace( $pattern, '', $search );
    }
    return $search;
}

如果你使用了 MobilePress 插件,移动设备访问的时候,希望搜索结果也返回加密文章,如上同样添加代码到 MobilePress 下的主题文件的 functions.php 中即可。

使登录用户的搜索结果包含私密文章的代码

function include_password_posts_in_search( $query ) {
	if ( is_user_logged_in() )
		$query->set( 'post_status', array ( 'publish', 'private' ) );
	}
add_action( 'pre_get_posts', 'include_password_posts_in_search' );

以上两个代码只能使用其中一个,因为我不知道怎么才能将其合到一起同时达到两种效果。

参考链接

  1. Include password protected posts in search results
  2. Display private posts in the WP search results for logged in users

2 comments on “使 WordPress 的搜索结果包含加密或私密文章

回复 中国梦 取消回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注