Php 用于主页的特定类别的循环
对于我的主页,我希望显示特定类别(例如“食品”类别)的帖子,而不是所有帖子的默认显示 如何做到这一点?我应该使用Php 用于主页的特定类别的循环,php,wordpress,Php,Wordpress,对于我的主页,我希望显示特定类别(例如“食品”类别)的帖子,而不是所有帖子的默认显示 如何做到这一点?我应该使用wp\u query()并避免query\u posts(),这是真的吗? 另外,我是否需要使用wp_reset_postdata()重置 我读过《抄本》并在谷歌上搜索过,但对改变循环仍然没有信心 我原以为下面的代码行得通,但我在WordPress主题2012和2013中看到了死亡的白屏。我将index.php中的代码替换为 <?php $query = new WP_Query
wp\u query()
并避免query\u posts()
,这是真的吗?
另外,我是否需要使用wp_reset_postdata()重置在index.php
中为该循环编写代码>
我读过《抄本》并在谷歌上搜索过,但对改变循环仍然没有信心
我原以为下面的代码行得通,但我在WordPress主题2012和2013中看到了死亡的白屏。我将index.php
中的代码替换为
<?php
$query = new WP_Query('cat=1');
if ($query->have_posts()) :
while ($query->have_posts()) : $query->the_post();
the_title();
endwhile;
endif;
?>
.
.
编辑:
我在下面使用了Pieter Goosen的解决方案。问题已修复。您不应更改主页或任何存档页上自定义查询的主查询。自定义查询用于辅助内容,而不是显示主内容。我已经在WPSE上就这件事做了一个非常详细的帖子,你可以查看。它还介绍了为什么您不应该使用查询帖子
要解决您的问题,请从index.php中删除您的自定义查询,只需添加默认的循环,如
if(have_posts()){
while(have_posts()) {
the_post();
//YOUR LOOP ELEMENTS
}
}
现在,您将再次在主页上看到所有帖子。要仅在主页上显示所选类别,请在执行主查询之前使用pre\u get\u post
更改主查询。将其添加到functions.php中
function show_only_category( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( 'cat', '1' );
}
}
add_action( 'pre_get_posts', 'show_only_category' );
这也将解决分页问题
编辑
为了SO用户的利益,我已将我的答案从WPSE转发给同一OP
<?php
get_header(); ?>
<div id="container">
<div id="content" role="main">
<?php
$categories = get_categories(); //get all the categories
foreach ($categories as $category) {
$category_id= $category->term_id; ?>
<div><?php echo $category->name ?></div>
<?php
query_posts("category=$category_id&posts_per_page=100");
if (have_posts()) {
while (have_posts()) {
the_post(); ?>
<a href="<?php the_permalink();?>"><?php the_title(); ?></a>
<?php }
}
}
} ?>
</div>
</div>
这段代码没有中断,因此页面上其他地方可能有错误。你查过你的错误日志了吗?非常感谢Pieter!这是完美的工作和分页工作!我对术语有点困惑。“自定义查询”是否总是这样:--$query=new WP_query('cat=1');------?我很困惑,因为我在------中没有看到这个确切的代码。另外,query\u posts()也被称为自定义查询吗?我对术语感到困惑也是因为------wp\u reset\u postdata()->最好在使用wp\u query创建自定义或多个循环之后使用------wp\u reset\u query()->最好在查询帖子循环后使用,以重置自定义查询------他将查询帖子称为自定义查询以下内容被使用并视为自定义查询,WP\u query
,get\u posts
和query\u posts
。关于循环的法典页写得很糟糕<不应使用代码>查询帖子
。使用WP\u Query
和get\u posts
创建的自定义查询应使用WP\u reset\u postdata()
重置query\u posts
应该用wp\u reset\u query
重置,谢谢你的帮助!不,您不需要重置主查询,这是在内部完成的。只需要重置自定义查询$wp_query
是主查询使用的全局值。要使主查询的对象在循环之外可用,您需要调用全局$wp\u query
,这样在您的函数中就正确了
<?php
get_header(); ?>
<div id="container">
<div id="content" role="main">
<?php
$categories = get_categories(); //get all the categories
foreach ($categories as $category) {
$category_id= $category->term_id; ?>
<div><?php echo $category->name ?></div>
<?php
query_posts("category=$category_id&posts_per_page=100");
if (have_posts()) {
while (have_posts()) {
the_post(); ?>
<a href="<?php the_permalink();?>"><?php the_title(); ?></a>
<?php }
}
}
} ?>
</div>
</div>