我有这段代码,它列出了我所有的类别(大约 10 个)。但是我在有一个类="活动"时遇到了问题。在我的代码下面,它使我的所有链接都处于活动状态。我该怎么做/指定链接必须是类为活动的链接?
我知道我有点接近,但我真的被困住了我该怎么做。我再次希望有人可以纠正/借给我一些帮助。
$terms = get_terms('portfolio_category');
$url = get_bloginfo('url');
$base = basename($_SERVER['REQUEST_URI'], '?' . $_SERVER['QUERY_STRING']);
$title_slug = basename(get_permalink()) ;
foreach ( $terms as $term) {
$class = 'class ="active"';
if($base == $title_slug){
?>
<a <?php echo $class; } ?> href="<?php echo $url; ?>/portfolio/<?php echo $term->slug; ?>"> <?php echo $term->name.'<br />'; ?> </a>
<?php } ?>
尝试更改foreach
中的if
语句:
$class = $base == $title_slug ?'class ="active"' : '';if($base == $term->slug){.......
更改您的代码块:-
foreach ( $terms as $term) {
$class = ($base == $title_slug) ? 'class ="active"' : '';
?>
<a <?php echo $class; ?> href="<?php echo $url; ?>/portfolio/<?php echo $term->slug; ?>"> <?php echo $term->name.'<br />'; ?> </a>
<?php } ?>
在我的情况下,这个对我有用。我应用了 Alaa 在 if
声明中的回复,它涉及到我需要的内容。
foreach ( $terms as $term) {
$class = ($base == $term->slug) ? 'class ="active"' : '';
?>
<a <?php echo $class; ?> href="<?php echo $url; ?>/portfolio/<?php echo $term->slug; ?>"> <?php echo $term->name.'<br />' ?> </a>
<?php } ?>
我想你应该尝试这样的事情
foreach ( $terms as $term) {
$class = $base == $title_slug ? 'class ="active"' : '';
?>
<a <?php echo $class; ?> href="<?php echo $url . '/portfolio/' . $term->slug; ?>"><?php echo $term->name; ?></a><br />
<?php } ?>
此外,最好将<?php ?>
替换为短标签版本<?= ?>