[英]Wordpress posts from the same category below post
I'm making a wordpress theme. 我正在做一个WordPress主题。 Right now I'm stuck with something.
现在,我陷入了困境。 I want to show the posts from the same category within the loop on a single post.
我想在单个帖子中显示循环中来自同一类别的帖子。 "Aktuelt for deg" is where the posts from the same category should be shown.
应显示“ Aktuelt for deg”(同度的职位)。 Live preview.
实时预览。 This is my code:
这是我的代码:
<?php get_header(); ?>
<div id="hold" class="clearfix">
<div id="left">
<?php if(have_posts()) : ?><?php while(have_posts()) : the_post(); ?>
<div class="entry">
<h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
<div class="author">Skrevet av <?php the_author(); ?></div>
<?php the_content(); ?>
</div>
<div class="comment-template">
<?php comments_template(); ?>
</div>
</div>
<div id="right">
<div class="search">
<form action="<?php echo home_url( '/' ); ?>" method="get">
<input type="text" value="Skriv her for å søke.." name="s" id="s" onblur="if (this.value == '') {this.value = 'Skriv her for å søke..';}"
onfocus="if (this.value == 'Skriv her for å søke..') {this.value = '';}">
</form>
<script type="text/javascript">
$(".search").keypress(function(ev){
if (ev.keyCode == 13) {
$("form")[0].submit();
}
});
</script>
</div>
<div class="box">
<div class="heading">
<h1>Aktuelt for deg</h1>
</div>
<ul>
<?php query_posts('posts_per_page=5' . '&orderby=rand');
while ( have_posts() ) : the_post();
echo '<li><div class="borderline"><a href="';
the_permalink();
echo '">';
the_title();
echo '</a></div><author>Skrevet av ';
the_author();
echo '</author></li>';
endwhile;
// Reset Query
wp_reset_query();
?>
</ul>
</div>
</div>
</div>
<?php endwhile; ?>
<?php endif; ?>
<?php get_footer(); ?>
Don't use query_posts
. 不要使用
query_posts
。 It's not the right tool for what you're trying to do. 这不是您要执行的操作的正确工具。
Use a WP_Query
instead: 请改用
WP_Query
:
global $post;
$current_category = get_the_category();
$same_category = new WP_Query(array(
'cat' => $category[0]->cat_ID,
'post__not_in' => array($post->ID),
'orderby' => 'rand',
'posts_per_page' => 5
));
Then, to render it, use this: 然后,使用以下命令进行渲染:
<?php while ( $same_category->have_posts() ) : $same_category->the_post(); ?>
<li>
<div class="borderline">
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
</div>
<author>Skrevet av <?php the_author(); ?></author>
</li>
<?php endwhile; ?>
For anyone else who stumbled upon this question later on: 对于以后偶然发现此问题的其他人:
Joseph Silber's code is almost correct. Joseph Silber的代码几乎是正确的。
'cat' => $category[0]->cat_ID,
Should be 应该
'cat' => $current_category[0]->cat_ID,
Because $category is not defined anywhere. 因为$ category没有在任何地方定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.