【问题标题】:Insert content after first post in WordPress loop在 WordPress 循环中的第一篇文章后插入内容
【发布时间】:2020-01-15 00:18:13
【问题描述】:

我想在 index.php 的循环中在第一个帖子之后显示一个类别列表(这是我的 WP 主题用来显示帖子的模板)。

我在网上四处搜索,发现了一些代码(见下文),它应该可以按照我的意愿执行 - 将类别标题列表作为循环中帖子列表之间的链接注入。

但是,它没有按预期工作。它只显示一个类别标题,而不是全部。有趣的是,它显示了第一个帖子类别的标题(自定义代码之前的帖子),但没有其他内容。

我的Loop代码,包括我插入的自定义代码如下:

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

<?php get_template_part('content'); ?>

// START CUSTOM CODE

<div>

<?php 
if( $wp_query->current_post == 0 ) { 
  $categories = get_the_category();
  $separator = ' ';
  $output = '';
  if($categories){
    foreach($categories as $category) {
        $output .= '<a href="'.get_category_link( $category ).'" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '">'.$category->cat_name.'</a>'.$separator;
    }
    echo trim($output, $separator);
  }
} 

?>

</div>

// END CUSTOM CODE

<?php endwhile; ?>  

希望有人能提供帮助。

谢谢,

湄公河

【问题讨论】:

    标签: php wordpress loops


    【解决方案1】:

    您的问题对我来说有点不清楚,但您似乎想要一个所有类别的列表,对吗?我认为“$categories = get_the_category();”这一行仅获取当前(在本例中为第一个)帖子的类别。

    如果您想要您的博客/网站中存在的所有类别的列表,请尝试“get_categories”,https://developer.wordpress.org/reference/functions/get_categories/

    【讨论】:

      【解决方案2】:

      试试这个代码,对你的代码做些小改动......

       <?php if (have_posts()) : $i = 1; while (have_posts()) : the_post(); ?>
      
      <?php get_template_part('content'); ?>
      
      <div class="categories">
      
      <?php 
      if( $i == 1){
      
          $categories = get_categories( array(
              'orderby' => 'name',
              'parent'  => 0
          ) );
      
          foreach ( $categories as $category ) {
              printf( '<a href="%1$s">%2$s</a><br />',
                  esc_url( get_category_link( $category->term_id ) ),
                  esc_html( $category->name )
              );
          }
      }
      ?>
      
      </div>
      
      
      <?php $i++; endwhile; ?>  
      

      【讨论】:

        最近更新 更多