php - Show category names for each post inside a loop in Wordpress -
i'm modifying pre-built theme display 3 'featured posts' before main grid of posts on index.php home page. thought best way loop before main loop queries posts category 'featured'. need display title of post post categories in front of background image of post thumbnail.
however, when use the_category(); background image no longer clickable , seems anchor tag duplicates , closes around every element in loop. code 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(); ?>
everything works fine until add the_category();.
now when inspect boxes 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>
the anchor link "my-favorite-bag" (the permalink) duplicated on , on again. also, category not enclosed in span class of "cat", expect.
why happen when add the_category or get_the_category?
how show categories each post in loop?
the easiest way category passing get_the_category()
function current post id.
$post_id = get_the_id(); // or use post id if have $category_object = get_the_category($post_id); $category_name = $category_object[0]->name;
the get_the_category()
function returns object contains properties such category id, it's name, etc...
also, note when using multiple wordpress loops, may have call wp_reset_postdata()
reset original query.
you can read more here:
Comments
Post a Comment