wordpress首页只显示某个分类的文章/插件实现(完美实现,附插件源码)

wordpress首页只显示某个分类的文章/插件实现(完美实现)

——————————————–插件源码—————————————————————-

<?php
/*
Plugin Name: Front Page Included-only Categories
Version: 0.2
Plugin URI:
Description: This version uses a comma separated list of *included* category ids.
Author: fengyqf
Author URI: http://www.path8.net/
*/

function fpe_where($where) {
// Change the $cats_to_include string to the category id you do not want to appear on the front page.
// Example:  $cats_to_include = ‘1, 2, 3, 4’;
$cats_to_include = ’22, 26′;

global $wpdb, $wp_query;

if (! $wp_query->is_home || strlen($cats_to_include) == 0) {
return $where;
}

if (empty($wpdb->term_relationships))
{
$where .= ” AND $wpdb->post2cat.category_id IN (” . $cats_to_include . “)”;
}
else
{
$where .= ” AND $wpdb->term_taxonomy.term_id IN (” . $cats_to_include . “)”;
}
return $where;
}

function fpe_join($join) {
global $wpdb, $wp_query;

if (!$wp_query->is_home) {
return $join;
}
if (empty($wpdb->term_relationships))
{
$join .= ” LEFT JOIN $wpdb->post2cat ON $wpdb->post2cat.post_id = $wpdb->posts.ID “;
}
else
{
if (!preg_match(“/$wpdb->term_relationships/i”,$join))
{
$join .=” LEFT JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id) “;
}
if (!preg_match(“/$wpdb->term_taxonomy/i”,$join))
{
$join .=” LEFT JOIN $wpdb->term_taxonomy ON $wpdb->term_taxonomy.term_taxonomy_id = $wpdb->term_relationships.term_taxonomy_id”;
}
}
return $join;
}

function fpe_distinct($distinct) {
global  $wp_query;

if (! $wp_query->is_home ) {
return $distinct;
}
return “distinct”;
}

add_filter(‘posts_join’, ‘fpe_join’);
add_filter(‘posts_where’, ‘fpe_where’);
add_filter(‘posts_distinct’, ‘fpe_distinct’);

?>

—————————————–插件源码 end——————————————————————-

简介:

该插件是一个wordpress插件 Front Page Excluded Categories基本上稍做修改而成,在此感谢前人的工作。

使用方法:

1. 安装,就是wordpress插件安装,这里就不用说了。

2. 配置,该插件没有管理界面,直接编辑源代码进行配置,需要编辑修改的只有如下的一行。

$cats_to_include = ’22, 26′;

该行在上面源码中已经标红,等号右边是一个引号括起来的以逗号分隔的数字,可以有一个或者多个,我在这里配置了两个22与26。数字即是需要显示在首页分类的id编号,该数字可以在wordpress后台的编辑“文章分类目录”、编辑分类时,在浏览器地址栏url里查看到。

原理:

只要简单的懂得一点php/mysql程序知识,比较一个这里的代码与Front Page Excluded Categories的差异部分(上面代码里已经标绿)就明白了。

插件下载:

front-page-included-categories

发表评论?

11 条评论。

  1. 不错,试了一下,确实可以。
    但是用了这个插件之后,首页最新文章里也只显示指定的分类目录的文章了。
    如果我还是希望最新文章里显示所有的文章该怎么解决呢?

    • 很抱歉,不知道怎么解决。这个插件功能太有限,个人对wordpress插件编写还不懂。

  2. 如果要排除指定分类的文章 是不是在分类ID前面加-号就行了呢

    • 不是,这个插件只有“只显示指定分类”的功能。如不显示指定分类的插件很多,建议google一下:http://www.google.com.hk/search?hl=zh-CN&lr=&newwindow=1&safe=strict&biw=1437&bih=659&as_qdr=all&q=wordpress+%E4%B8%8D%E6%98%BE%E7%A4%BA%E6%8C%87%E5%AE%9A%E5%88%86%E7%B1%BB&aq=f&aqi=&aql=&oq=

  3. 顺利解决问题,非常的感谢!!!
    必须顶一下!!!!!!!!!!!

  4. 终于搞定了,太感谢了!!真插件太好了!!!

  5. 谢谢提供的解决方案

  6. 为什么我试了一下,首页还是不显示分类目录下的文章标题呢?

发表评论