2012-09-09 19 views
1

我正在做一个wordpress主题。现在我陷入了困境。我想在单个帖子的循环中显示来自同一类别的帖子。 “deg的Aktuelt”是应该显示来自同一类别的帖子的地方。 Live preview.这是我的代码:以下同一类别的WordPress的帖子

<?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(); ?> 

回答

4

不要使用query_posts。这不是你想要做的事情的正确工具。

使用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 
)); 

然后,以使其使用这样的:

<?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; ?> 
+0

这不到风度获得来自同一类别的职位...? –

+0

@VemundEldegard - 你是说它确实*不*让你从同一类别的帖子? *你得到了什么? –

+0

- 我收到所有其他帖子,而不是同一类别的帖子。 –

相关问题