2013-07-10 34 views
2

我有分組meta_values的問題。 查詢查找metakey「company」的帖子。我想要一個獨特的顏色列表,如:藍色紅色黃色Wordpress循環 - Meta_Key只有唯一值

array_unique不成功,也自定義mysql查詢。

<?php 
$args = array(
     'category_name' => $cat_name, 
     'posts_per_page' => '60', 
     'paged' => $current_page, 
     'meta_query' => array(
      array(
       'key' => 'company', 
       'value' => 'microsoft', 
       'compare' => 'like' 
      ) 
     ) 
    ); 
$my_query = new WP_Query($args); 
while ($my_query->have_posts()) : $my_query->the_post(); 
$do_not_duplicate = $post->ID; 
?> 

<?php echo get('color'); ?> 
// Outputs yellow yellow blue yellow red yellow 

<?php endwhile; ?> 

電流輸出爲:黃黃,藍,黃紅,黃,

感謝。

編輯:

感謝您的幫助!

這是最後的工作代碼:

<?php 
$current_page = (get_query_var('paged')) ? get_query_var('paged') : 1; 
$cat_name = get_category(get_query_var('cat'))->name; 


$args = array(
    'category_name' => $cat_name, 
    'posts_per_page' => '60', 
    'paged' => $current_page, 
    'meta_query' => array(
     array(
      'key' => 'company', 
      'value' => 'microsoft', 
      'compare' => 'like' 
     ) 
    ) 
); 
$my_query = new WP_Query($args); 
while ($my_query->have_posts()) : $my_query->the_post(); 
$do_not_duplicate = $post->ID; 
$colors[] = get('color'); 

// Creates an array of all colors 

endwhile; 
$colors = array_unique($colors); 
// Removes duplicates; 
foreach($colors as $color){ 
echo $color.' '; 
} ?> 
+0

這是否包含任何幫助嗎? http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_distinct –

+0

嘿謝謝,但沒有工作。似乎只用於插件。不知道該怎麼做。已經搜索了整個網絡。 – mistertodd

回答

2
while ($my_query->have_posts()) : $my_query->the_post(); 
    $do_not_duplicate = $post->ID; 
    $colors[] = get('color'); 
    // Creates an array of all colors 

endwhile; 
$colors = array_unique($colors); 
// Removes duplicates; 
foreach($colors as $color){ 
    echo $color; 
} 
+0

不,仍然有重複的顏色。 :-(我不明白,爲什麼不能正常工作? – mistertodd

+0

現在工作正常!!!!已將array_unique($ colors);'改爲'$ colors = array_unique($ colors); ' – mistertodd

+0

這可能是一個足夠好的解決方案來解決你的問題,但是,想象一下從數據庫中取出10000行的情況,看看是否有三個顏色組。如果可能的話,應該在mysql方面做得更好:) –