添加正确数量的逗号

时间:2014-11-03 11:58:42

标签: php wordpress

此脚本显示帖子的类别,但不包括用户不想显示的帖子:

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;
   }
  }
 }
}

这样的触发功能。

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

因此,如果一个帖子有类别:1,2,3,4,5只回显1,2,3,4。

该脚本适用于具有排除类别(5)的帖子。

问题在于没有该类别的帖子。

所以,如果帖子有类别:1,2,3,4那些被回应,但逗号少于所需:1,2,34

对于没有必须排除的类别的帖子,$ thecount变量总是计算错误。

2 个答案:

答案 0 :(得分: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);

要使其支持单值输入 - 这样您就可以指定一个或多个要排除的类别。

答案 1 :(得分: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;

}