2016-02-02 175 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

相關問題