2016-02-02 178 views
0

我正在修改预先构建的主题以在index.php主页上的所有帖子的主网格之前显示3个“精选帖子”。我认为这样做的最好方法是在查询具有“精选”类别的帖子的主循环之前执行另一个循环。我需要它显示帖子的标题以及帖子缩略图背景图像前的帖子类别。显示Wordpress中循环内每个帖子的类别名称

但是,当我使用the_category();背景图片不再是可点击的,并且似乎锚标签重复并在循环中的每个元素周围自行关闭。我的代码如下:

<?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(); 
?> 

一切工作正常,直到我添加the_category();.

现在,当我检查了盒子我看到这一点:

<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_category或get_the_category时才会发生这种情况?

如何在此循环中显示每篇文章的类别?

+0

检查页面源代码,并在可能的情况下将相关部分添加到您的问题中 – Trix

回答

1

获取类别的最简单方法是将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; 

get_the_category()函数返回一个包含属性,如类别ID的对象,它的名字,等..

另外,还要注意使用多个WordPress的循环时,您可能需要调用wp_reset_postdata()到重置为原始查询。

你可以在这里阅读更多:

Wordpress Wp_Query

get_the_category()

1

你可以在许多方式获得类别名称:

后循环中,如果你的职位只有一个类别,然后用作:

$ cats = get_the_category(); $ cat_name = $ cats [0] - > name;

如果您的帖子有两个以上的类别,那么您可以查找get_the_category_list()。

参考链接:https://codex.wordpress.org/Function_Reference/get_the_category_list

获取此类别的链接,您可以使用 $ category = get_the_category(); echo'cat_ID)。'“> cat_name。'”alt =“'。$ category [0] - > cat_name。''/>';

使用类别归档文件时(可以在循环之前使用该类别归类到$ cat_name变量): $ cat_name = get_category(get_query_var('cat')) - > name; 参考链接:http://codex.wordpress.org/Function_Reference/get_category

相关问题