Php 添加正确数量的逗号
此脚本显示帖子的类别,但不包括用户不想显示的类别:Php 添加正确数量的逗号,php,wordpress,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_categ
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变量对于没有必须排除的类别的帖子总是计算错误。尝试以下方法:
$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);
要使其也支持单值输入,您可以通过这种方式指定一个或多个要排除的类别。找到了解决此问题的更好方法:
if( !is_array($exclude)) $exclude = array($exclude);
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;
}