首页 文章

如何修改wordpress主循环?

提问于
浏览
1

我有一个基于wordpress(二十三子模板)的单页网站 . Headers 内容页脚 . 和3个帖子类别:类别A类别B类别C.我需要将内容分成这3个类别/部分 - 就像这样

<div class="section_top">
  all the posts from category A
</div>
<div class="section_mid">
  all the posts from category B
</div>
<div class="section_bot">
  all the posts from category C
</div>

当我开始阅读wordpress主循环,query_posts和WP_Query时,我有点困惑,最终我有这个代码替换主循环,所以我的问题是:

1这是正确的方法吗?

2如何给每个部分一个独特的类,因为我需要对每个部分进行不同的样式设置?

这是代码(索引php(在子主题中)

<div id="primary" class="content-area">

    <div id="content" class="site-content" role="main"> 

<?php

$args = array('category__in' => array(catA,catB,catC));
$category_posts = new WP_Query($args);
if($category_posts->have_posts()) : 
  while($category_posts->have_posts()) : 

     $category_posts->the_post();

?>

  <div id="<?php
  foreach((get_the_category()) as $category) {echo $category->cat_name . ' ';}?>"
     class="post-item">
              <div class="post-info">
        <h2 class="post-title">
        <a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>">
        <?php the_title(); ?>
        </a>
        </h2>
      </div>
      <div class="post-content">
      <?php the_content(); ?>
      </div>
    </div>


<?php
  endwhile;
else: 
?>
  Oops, there are no posts.
<?php
endif;
?>

1 回答

  • 1

    您尝试解决问题的方法是所有帖子仍按时间顺序显示,因此可能会发生这种情况:

    Category A post 12/01
    Category B post 09/01
    Category A post 05/01
    

    我建议:制作3个不同的WordPress循环,分别查询每个类别,如下所示:

    <div class="section_top">
       WordPress loop for all the posts from category A
    </div>
    <div class="section_mid">
      WordPress loop for all the posts from category B
    </div>
    <div class="section_bot">
      WordPress loop for all the posts from category C
    </div>
    

    这样一个循环的例子:

    // The Query
    $the_query = new WP_Query('category_name=categoryA');
    
    // The Loop
    if ( $the_query->have_posts() ) {
            echo '<ul>';
        while ( $the_query->have_posts() ) {
            $the_query->the_post();
            echo '<li>' . get_the_title() . '</li>';
        }
            echo '</ul>';
    } else {
        // no posts found
    }
    /* Restore original Post Data */
    wp_reset_postdata();
    

    Difference between get_the_...() and the_...()

    当您使用 get_the_title() 之类的函数时,您可以将它们存储在PHP变量中,如下所示:

    $title = get_the_title();
    echo strtoupper($title); //do something with it later
    

    当您使用 the_title() 等函数时, Headers 会立即打印在页面上,因此不需要echo语句:

    the_title();
    

    注意: the_permalink() 有一个函数 get_permalink() ,函数 get_the_permalink() 不存在 . 不要问我为什么;)

相关问题