在WordPress循环中的第一篇文章之后插入内容

问题描述 投票:-1回答:2

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

我已经在网上搜索了一些代码(请参阅下文),该代码应该按我的意愿进行-插入类别标题列表作为循环中帖子列表之间的链接。

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

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

<?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
2个回答
0
投票
我对您的问题有点不清楚,但似乎您想要一个[[all类别列表,对吗?我认为这行“ $ categories = get_the_category();”仅获取当前(在此情况下为第一个)帖子的类别。

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


0
投票
<?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; ?>
© www.soinside.com 2019 - 2024. All rights reserved.