環路

2013-06-20 26 views
0

避免重複項目我寫了一個查詢,以顯示在WordPress的, 相關職位的簡要說明: 首先,它會檢查哪些類別目前的職位屬於, 進而提出「彈頭」的名稱,一個陣列內的類別(」 $ cats「) 然後使用foreach,我查詢具有相同分類法的帖子。 此代碼的效果很好,除了當前帖子屬於多個類別並且還有另一個帖子屬於這些類別時,在這種情況下,其他帖子會顯示兩次或甚至更多,具體取決於它們共享的分類數量,環路

所以問題是,我如何檢查一個帖子是否重複以及如何防止它? 代碼:

<?php 
$terms = get_the_terms($currentid, 'taxonomy'); 
$cats = array_map(function($a){ return $a->slug; }, $terms); 

    foreach ($cats as $cat) { 
     $args=array(
    'taxonomy' => $cat , 
    'post_type' => 'apps', 
    'post_status' => 'publish', 
    'posts_per_page' => 4, 
); 
global $wp_query; 
$wp_query = new WP_Query($args); 
    while ($wp_query->have_posts()) : $wp_query->the_post(); 
    if($currentid !== get_the_ID()){ 


    ?> 

    <li><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"> 
    <?php 
    if (has_post_thumbnail()){ 
    $appfetured  = wp_get_attachment_image_src(get_post_thumbnail_id(get_the_ID())); 
    $appfeturedimage = $appfetured[0]; 
    }else{ 
    $appfeturedimage = '../img/defaultappicon.png'; 
    } 
    ?> 
    <img class="appfeatured" src="<?php echo $appfeturedimage; ?>" alt="<?php the_title_attribute(); ?>" /> 
    </a> 
    </li> 
    <?php 
    } 
    endwhile; 

wp_reset_query(); // Restore global post data stomped by the_post(). 
}//end foreach 
?> 
+0

理想情況下,你會構造一個查詢,搜索_a一次只能返回類別,並且只返回唯一的帖子。然而,與wordpress保持安全的距離,我不知道''taxonomy'=> $ cats'在'WP_Query'參數中是否有效,但我的確可以想象它可以被轉換爲一個很好的IN()子句。 .. – Wrikken

回答

0

如果你正在嘗試做的就是讓所有的職位在所有類別的當前職位試試這個:

<?php 
    $args = array(
     'cat'   => wp_get_post_categories($currentid), 
     'post_type'  => 'apps', 
     'post_status' => 'publish', 
     'posts_per_page' => 4 
    ); 

    new WP_Query($args); 

這已經有一段時間,因爲我」已經使用WordPress的,所以我不知道是否有類別和分類之間的差異,所以你可以試試這個:

<?php 
    terms = get_the_terms($currentid, 'taxonomy'); 
    $cats = array_map(function($a){ return $a->slug; }, $terms); 

    $args = array(
     'taxonomy' => $cats, 
     'post_type' => 'apps', 
     'post_status' => 'publish', 
     'posts_per_page' => 4, 
    ); 

    global $wp_query; 
    $wp_query = new WP_Query($args);