WordPress category.php在使用query_posts时不按类别排序

时间:2014-07-23 20:16:39

标签: php wordpress categories

我正在将SuperSimple主题用于wordpress博客,并尝试自定义category.php页面。我希望在所有旧帖子的较小网格之上为每个类别中的最新帖子提供一个大图像。

到目前为止,我按照我想要的方式工作,除了顶部图片(div id="post1")只是最新的帖子,而不是该类别的最新帖子。以下是其中一个类别页面:http://meanmargie.com/category/hospitality/

这是我的代码:

<header class="header">
<h1 class="entry-title"><?php single_cat_title(); ?></h1>
<?php if ( '' != category_description() ) echo apply_filters( 'archive_meta', '<div class="archive-meta">' . category_description() . '</div>' ); ?>
</header>

<div id="post1">
<?php query_posts('showposts=1'); if ( have_posts() ) : while ( have_posts() ) : the_post(); ?><?php if ( has_post_thumbnail() ) { the_post_thumbnail('featured'); } ?>
<div id="post-info"><a href="<?php the_permalink(); ?>"title="<?php the_title_attribute(); ?>" rel="bookmark"><?php the_title(); ?></a><br><a href="<?php echo get_permalink(); ?>"> Read More</a></div>
<?php endwhile; endif;  wp_reset_query();?>
</div>
<br>

<div id="post2">
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?><?php if ( has_post_thumbnail() ) { the_post_thumbnail('medium'); } ?>
<div id="post-info"><a href="<?php the_permalink(); ?>"title="<?php the_title_attribute(); ?>" rel="bookmark"><?php the_title(); ?></a><br><a href="<?php echo get_permalink(); ?>"> Read More</a></div>
<?php endwhile; endif; ?>
</div>

2 个答案:

答案 0 :(得分:0)

首先,使用get_query_var('cat')

返回您所在类别页面的类别ID
$category = get_query_var('cat');
  $cat_id = $category->cat_ID;

现在,使用'cat'=> $cat_id,将该ID返回WP_Query。请注意,showposts已弃用,请改用posts_per_page

请勿使用 query_posts。你永远不应该使用query_posts。它会破坏并改变主查询,并且在大多数情况下都会以分页方式完全失败。

答案 1 :(得分:0)

以下是我最终使用的解决方案:

<div id="post1">
<?php //new query to limit number of posts
    $wp_query = new WP_Query();
    $wp_query->query($query_string."&posts_per_page=1&paged=".$paged);
?>
<?php WP_Query; if ( have_posts() ) : while ( have_posts() ) : the_post(); ?><?php if ( has_post_thumbnail() ) { the_post_thumbnail('featured'); } ?>
<div class="caption"><a href="<?php the_permalink(); ?>"title="<?php the_title_attribute(); ?>" rel="bookmark"><?php the_title(); ?></a></div><div class="excerpt"><a href="<?php echo get_permalink(); ?>"> Read More</a></div>
<?php endwhile; endif; wp_reset_query();?>
</div>