我正在尝试根据我拥有的类别数创建一个网址。我想要的预期输出是:
<a href="http://lart.co.uk/?cat=13" title="Category Name">Dance</a>
<a href="http://lart.co.uk/?cat=19" title="Category Name">Fashion</a>
我得到的输出是:
<a href="http://lart.co.uk/?cat=13" title="Category Name">
<a href="http://lart.co.uk/?cat=19" title="Category Name">
Dance</a> Fashion</a> </a>
这几乎是我想要的,但很明显我还有很多。我正在使用3个foreach语句来获得此结果。我试过筑巢一个foreach但是没有用。问题是将一个foreach的结果传递给另一个foreach。
这是我正在使用的代码:
<?php
$categories = get_the_category();
$separator = ', ';
if($categories) {
foreach($categories as $category) {
$output .= $category->cat_name.$separator;
$cat_id[] = $category->cat_ID;
}
foreach($cat_id as $id) {
$category_link = get_category_link( $id ); ?>
<a href="<?php echo esc_url( $category_link ); ?>" title="Category Name">
<?php }
$strarr = explode(',',$output);
foreach($strarr as $string) {
echo $string .'</a>';
}
} ?>
答案 0 :(得分:4)
这样简单得多就足够了:
$categories = get_the_category();
foreach ($categories as $category) {
printf('<a href="%s" title="Category Name">%s</a>',
htmlspecialchars(get_category_link($category->cat_ID)),
htmlspecialchars($category->cat_name));
}
您只需循环浏览类别,每个类别输出一个链接。没什么。
答案 1 :(得分:1)
你使自己变得复杂,我已经纠正了你的代码
<?php
$categories = get_the_category();
$separator = ', ';
if($categories) {
foreach($categories as $category) {
$output .= $category->cat_name.$separator;
$cat_id[] = $category->cat_ID;
}
foreach($cat_id as $id) {
$category_link = get_category_link( $id );
$cat_name = get_cat_name($id);?>
<a href="<?php echo esc_url( $category_link ); ?>" title="<?php echo $cat_name;?>"><?php echo $cat_name; ?></a>
<?php
}
}
?>
codex:http://codex.wordpress.org/Function_Reference/get_cat_name
答案 2 :(得分:0)
试试这个:
<?php
$categories = get_the_category();
$separator = ', ';
if($categories) {
foreach($categories as $category) {
$output .= $category->cat_name.$separator;
$cat_id[] = $category->cat_ID;
}
foreach($cat_id as $id) {
$category_link = get_category_link( $id ); ?>
<a href="<?php echo esc_url( $category_link ); ?>" title="Category Name">
<?php
$strarr = explode(',',$output);
foreach($strarr as $string) {
echo $string .'</a>';
}
}
} ?>