njp*_*ten 2 html php wordpress wordpress-theming
I'm modifying a pre-built theme to display 3 'featured posts' before the main grid of all posts on the index.php home page. I thought that the best way to do this was to do another loop before the main loop that queries posts with the category 'featured'. I need it to display the title of the post as well as the post categories in front of a background image of the post thumbnail.
However, when I use the_category(); the background image is no longer clickable and it seems that the anchor tag duplicates and closes itself around every element in the loop. My code is as follows:
<?php
$query = array(
'posts_per_page' => 3,
'post_type' => 'post',
'category_name' => 'featured',
'orderby' => 'date',
'order' => 'DESC'
);
$featured_home = new WP_Query( $query );
if( $featured_home->have_posts() ) {
?>
<div class="container featured-home">
<?php while ( $featured_home->have_posts() ) : $featured_home->the_post();?>
<div class="featured-home-box">
<a href="<?php the_permalink(); ?>">
<div class="featured-home-img" <?php
if ( $thumbnail_id = get_post_thumbnail_id() ) {
if ( $image_src = wp_get_attachment_image_src( $thumbnail_id, 'normal-bg' ) )
printf( ' style="background-image: url(%s);"', $image_src[0] );
}?>>
<div class="blog-info-content">
<span class="cat"><?php the_category(); ?></span>
<h3><?php the_title(); ?></h3>
</div>
</div>
</a>
</div>
<?php
endwhile;
?>
</div>
<?php
}
wp_reset_postdata();
?>
Run Code Online (Sandbox Code Playgroud)
Everything works fine until I add the_category();.
Now when I inspect the boxes I see this:
<div class="featured-home-img" style="background-image: url(bag.jpg);">
<a href="my-favorite-bag/"></a>
<div class="blog-info-content">
<a href="my-favorite-bag/">
<span class="cat"></span>
</a>
<ul class="post-categories">
<a href="my-favorite-bag/"></a>
<li>
<a href="my-favorite-bag/"></a>
<a href="category-culture/" rel="category tag">Culture</a>
</li>
<li>
<a href="category-featured/" rel="category tag">Featured</a>
</li>
</ul>
<h3>My Favorite Bag</h3>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
带有“my-favorite-bag”(永久链接)的锚链接被一遍又一遍地复制。此外,正如我所料,该类别未包含在具有“cat”类的跨度中。
为什么只有在我添加 the_category 或 get_the_category 时才会发生这种情况?
如何显示此循环中每个帖子的类别?
获取类别的最简单方法是get_the_category()
将当前帖子 id传递给函数。
$post_id = get_the_ID(); // or use the post id if you already have it
$category_object = get_the_category($post_id);
$category_name = $category_object[0]->name;
Run Code Online (Sandbox Code Playgroud)
该get_the_category()
函数返回一个对象,其中包含类别 ID、名称等属性...
另请注意,当使用多个 wordpress 循环时,您可能需要调用wp_reset_postdata()
重置为原始查询。
你可以在这里阅读更多: