2014-11-03 66 views
1

的這個腳本顯示文章的類別,但不包括用戶不希望顯示的:添加正確的號碼逗號

function exclude_post_categories($excl='', $spacer=' ') { 
$categories = get_the_category($post->ID); 
    if (!empty($categories)) { 
    $exclude = $excl; 
    $exclude = explode(",", $exclude); 
    $thecount = count(get_the_category()) - count($exclude); 
    foreach ($categories as $cat) { 
    $html = ''; 
    if (!in_array($cat->cat_ID, $exclude)) { 
    $html .= '<a href="' . get_category_link($cat->cat_ID) . '" '; 
    $html .= 'title="' . $cat->cat_name . '">' . $cat->cat_name . '</a>'; 
     if ($thecount > 1) { 
     $html .= $spacer; 
     } 
    $thecount--; 
    echo $html; 
    } 
    } 
} 
} 

的fuctions被觸發這個樣子。

<?php exclude_post_categories('5', ', '); 

所以,如果一個職位有1,2,3,4,5的類別,只有1,2,3,4被迴應。

該腳本適用於排除了類別的帖子(5)。

問題在於沒有該類別的帖子。

所以,如果一個職位有三類:1,2,3,4,這些都回蕩但比需要較少的逗號:1,2,34

$ thecount變量始終計算錯誤的職位,沒有必須排除的類別。

回答

0

找到一個更好的解決這裏的問題:http://css-tricks.com/snippets/wordpress/the_category-excludes/#comment-1583708

function exclude_post_categories($exclude="",$spacer=" ",$id=false){ 
//allow for specifiying id in case we 
//want to use the function to bring in 
//another pages categories 
if(!$id){ 
    $id = get_the_ID(); 
} 
//get the categories 
$categories = get_the_category($id); 
//split the exclude string into an array 
$exclude = explode(",",$exclude); 
//define array for storing results 
$result = array(); 
//loop the cats 
foreach($categories as $cat){ 
    if(!in_array($cat->cat_ID,$exclude)){ 
     $result[] = "$cat->name"; 
    } 
} 
//add the spacer 
$result = implode($spacer,$result); 
//print out the result 
echo $result; 

} 
0

嘗試這樣:

$existing = get_the_category(); 

$newcategories = array_udiff($existing,$exclude,function($e,$x) { 
    return $e->cat_ID != $x; 
}); 

$as_links = array_map(function($c) { 
    return '<a href="'.get_category_link($c->cat_ID).'" ' 
     .'title="'.$cat->cat_name.'">'.$cat->cat_name.'</a>'; 
},$newcategories); 

echo implode($spacer, $as_links); 

這將第一剝離出其ID是$exclude陣列中的類別,然後每個類別轉換爲類別鏈接,與所述分離器輸出它們。

編輯:稍有誤解的問題。這期望$exclude是一個數組。把下面一行開始:

if(!is_array($exclude)) $exclude = array($exclude); 

爲了使其支持單值輸入以及 - 這種方式,您可以指定一個或多個類別來排除。