2015-02-23 22 views
-1

我想知道是否有可能以顯示wp_query內的置頂文章,並根據各自的類別他們理清:顯示置頂文章,並將它們整理出來,根據其類別

loop(
- the first sticky post has the category 1 
- the second sticky post has the category 2 
- the third sticky post has the category 1 
) 

,並應顯示:

- category 1: 
- the first sticky post 
- the third sticky post 
- category 2: 
the second sticky post 

與這個網站:

<div class="flex-6"> 
    <h4><?php 
    $category = get_the_category(); 
    echo $category[0]->cat_name; 
    ?></h4> 
    <ul class="list"> 
    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> 
    </ul> 
</div> 

我有科爾ECT循環的置頂文章:

$sticky = get_option('sticky_posts'); 
    $query = new WP_Query(array('post__in' => $sticky)); 
    if($query->have_posts()) : while($query->have_posts()) : $query->the_post(); 

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



    endwhile; endif; 

爲了促成最終的結果

<div class="flex-6"> 
    <h4>Category 1</h4> 
    <ul class="list"> 
    <li><a href="the_first_link">The first title</a></li> 
    <li><a href="the_third_link">The third title</a></li> 
    </ul> 
</div> 
<div class="flex-6"> 
    <h4>Category 2</h4> 
    <ul class="list"> 
    <li><a href="the_second_link">The secondtitle</a></li> 
    </ul> 
</div> 

任何idead? 感謝您的時間

回答

1

最簡單的方法是先拿到類別:

<?php 

$cat_args = array(
    'child_of'  => 0, 
    'orderby'  => 'name', 
    'order'   => 'ASC', 
    'hide_empty' => 1, 
    'taxonomy'  => 'category' 
); 
$cats = get_categories($cat_args); 

,然後循環通過它們獲得的職位:

$sticky = get_option('sticky_posts'); 
foreach ($cats as $cat) : 
    $args = array(
     'post_type'   => 'post', 
     'post__in'   => $sticky, 
     'posts_per_page' => -1, 
     'orderby'   => 'title', // or whatever you want 
     'tax_query' => array(
      array(
       'taxonomy' => 'category', 
       'field'  => 'slug', 
       'terms'  => $cat->slug 
      ) 
     ) 
    ); 
    $posts = get_posts($args); 
    if ($posts) : 
    ?> 

     <div class="flex-6"> 
     <h4><?php echo $cat->cat_name; ?></h4> 
     <ul class="list"> 
     <?php foreach ($posts as $post) : ?> 
     <li><a href="<?php echo get_permalink($post->ID); ?>"><?php echo get_the_title($post->ID); ?></a></li> 
     <?php endforeach; ?> 
    </ul> 
    </div> 
    <?php 
    endif; 
endforeach; 
+0

何人,你不知道如何我浪費了很多時間試圖做到這一點! 這個工作很棒,現在我會看線條以便更深入地理解。非常感謝你的幫助! – 2015-02-23 19:43:26

相關問題