当前位置: 首页 >wordpress

WordPress 排除指定分类以及不同分类显示不同内容

wordpress 2015-7-10 阅读量: 838 TAG:

WordPress 如何实现循环内排除指定分类以及不同分类显示不同内容?分享来自网络搜集的代码,同时也是给自己备忘。

WordPress 主循环外排除特定分类:

用途举例:一般 WordPress 主题的 index.php 都是输出所有分类的日志,但是对于不同的需求可以 DIY 一下,比如说你想隐藏某特定分类下的日志,让其不在首页显示,但是这又不同于私有日志,它是公开可见的。这时候就需要在 the loop 之外将此特定分类排除。

在 WordPress 默认模板中,主循环调用文章的代码格式如下:

<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
//主循环内容
<?php endwhile; ?>
<?php endif; ?>

默认情况下,文章调用范围为所有分类。如果排除某分类,可以使用 query_posts() 函数:

<?php query_posts(‘cat=-1’); ?>

以上代码调用除分类 ID 为 1 外的所有文章。将其插入主循环前即可。

由于 query_posts() 函数会与分页功能造成冲突,可以将 query_posts() 语句替换为:

<?php
$limit = get_option(‘posts_per_page’);
$paged = (get_query_var(‘paged’)) ? get_query_var(‘paged’) : 1;
query_posts(‘cat=-1&showposts=’ . $limit=10 . ‘&paged=’ . $paged);
?>

若需排除特定分类,又要保持分页功能正常,则完整代码如下:

<?php
$limit = get_option(‘posts_per_page’);
$paged = (get_query_var(‘paged’)) ? get_query_var(‘paged’) : 1;
query_posts(‘cat=-1&showposts=’ . $limit=10 . ‘&paged=’ . $paged);
?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
//主循环内容
<?php endwhile; endif; ?>

WordPress 主循环内排除特定分类:

用途举例:如果博主希望需要根据日志分类来显示不同的广告,这时候,你就需要用到 in_category 函数,在 the loop 之内排除 WordPress 的特定日志分类。

用法如下:

<?php
if ( in_category( ‘pachoderms’ )) {
// They have long trunks…
} elseif ( in_category( array( ‘Tropical Birds’, ‘small-mammals’ ) )) {
// They are warm-blooded…
} else {
// & c.
}
?>

其他示例

<?php
if ( in_category(‘fruit’) ) {
include ‘single-fruit.php’;
} elseif ( in_category(‘vegetables’) ) {
include ‘single-vegetables.php’;
} else {
// Continue with normal Loop
if ( have_posts() ) : while ( have_posts() ) : the_post();
// …
}
?>

in_category 函数的具体用法可以参见官方文件

 

(微信/QQ号:909912499),欢迎分享本文,转载请保留出处!部分内容来自网络,如有侵权请联系删除处理!

相关信息

本站提供代码修改,dedecms,WordPress仿站二次开发 / PHP网站建设以及SEO优化等网络营销推广等服务。

如有需要请加QQ: 909912499