让WordPress的私有文章(private post)所属的tags和categories显示出来

PHP, 技术心得 Add comments

  Wordpress有private post的功能,但是一个post一旦作为private被save而不是public,则不会在数据库中进行计数(不算在已发的文章中)。这里讨论了这个问题。
  现在问题在于,如果一个tag或者category只含有private post,那么它的计数是0,被认为是不含有文章从而不会被显示出来,哪怕是登录以后有权限看private post的情况下也是如此。这里,Wordpress的support forum的一个Moderator建议应该修改wp-includes中的taxonomy.php里的此处

function _update_post_term_count( $terms ) {
	global $wpdb;
 
	foreach ( (array) $terms as $term ) {
		$count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships, $wpdb->posts WHERE $wpdb->posts.ID = $wpdb->term_relationships.object_id AND post_status = 'publish' AND post_type = 'post' AND term_taxonomy_id = %d", $term ) );
		$wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
	}
}

  看起来似乎在 post_status = 'publish' 后面加一个 OR post_status = 'private' 就行了,但实际上没效果。为什么呢?这是往数据库中写的时候用来计数的,不是用来显示的;当我们已经有private post,修改这里并不会让本来被认为是空着的tag和category变得有数字。

  解决方案在这里,修改wp-includes中的category-template.php,function wp_tag_cloud( $args = '' ) 中的

$tags = get_tags( array_merge( $args, array( 'orderby' => 'count', 'order' => 'DESC' ) ) ); // Always query top tags

改为

$tags = get_tags( array_merge($args, array('hide_empty' => 0, 'orderby' => 'count', 'order' => 'DESC')) ); // Always query top tags

  也就是给 get_tags() (这其实是taxonomy.php里 get_term() 的一个封装,所以参数也一样)加上一个参数 'hide_empty' => 0 ,即显示被认为是空的tag。
  category也一样做就可以了,同样是category-template.php里,修改 function wp_list_categories( $args = '' ) 中的

$defaults = array(
		'show_option_all' => '', 'orderby' => 'name',
		'order' => 'ASC', 'show_last_update' => 0,
		'style' => 'list', 'show_count' => 0,
		'hide_empty' => 1, 'use_desc_for_title' => 1,
		'child_of' => 0, 'feed' => '', 'feed_type' => '',
		'feed_image' => '', 'exclude' => '', 'current_category' => 0,
		'hierarchical' => true, 'title_li' => __( 'Categories' ),
		'echo' => 1, 'depth' => 0
	);

  把 'hide_empty' => 1 改成0即可。
  当然,如果需要只让有权限看private post的用户看到这些变化,只要给前面两处修改加上 if(current_user_can("read_private_posts")) 这样的判断就行了。

Related posts:

  1. Directory Opus 联网验证被封证书后,清除安装痕迹的方法

8 Responses to “让WordPress的私有文章(private post)所属的tags和categories显示出来”

  1. 蓝天博客 Says:

    呵呵,来给南大校友捧场。百合一直是我喜爱的,至今难忘

  2. WG Says:

    感谢捧场;)

  3. Jessica Says:

    如果希望自己在檢視月曆時,能夠讓月曆顯示當天有寫私有文章,也是可以做一樣的更改嗎?

  4. WG Says:

    你好,虽然我没有尝试过,但是从理论上来说,这是一样的
    所以我认为应该是可以的,你不妨一试

  5. Hemorrhoids Says:

    I am amazed with it. It is a good thing for my research. Thanks. ^_^

  6. jc Says:

    能不能实现私有文章列表不隐藏,显示标题或者警告字句的效果?
    http://www.wordpress.org.cn/thread-53618-1-1.html

  7. WG Says:

    用密码+插件,既可以产生你要的效果,也可以批量修改密码、修改密码文章的标题
    这样的插件有很多

    否则就只有深入改代码了……

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">


LilyStudio & WordPress & N.Design Studio
Entries RSS Comments RSS Log in