Easy one, but I can't find an answer.
I wanna to list sub-categories to create tabs in code below. This one works fine in my output. But the first tab needs a <li class= "selected" >
to show the content on page load .
How to force the first echo result to include a class on <li>
element ?
.
.
.
[ Output ]
Actual: .......... Category 1 | Category 2 | Category 3
Needed: .......... Category 1* | Category 2 | Category 3
*class="selected"
<ul class="cd-tabs-navigation">
<?php
$argumentos = array(
'hide_empty' => 1,
'child_of' => 44,
);
$categories = get_categories($argumentos);
foreach($categories as $category) {
echo '<li><a data-content="' . $category->slug . '" href="#' . $category->slug . '">' . $category->name . '</a></li>';
}
?>
</ul>
.
.
[ EDIT ]
The solution by Lal. Thank you everyone!
foreach($categories as $category) {
if(++$i==1)
echo '<li class="selected"><a class="selected" data-content="' . $category->slug . '" href="#' . $category->slug . '">' . $category->name . '</a></li>';
else
echo '<li><a data-content="' . $category->slug . '" href="#' . $category->slug . '">' . $category->name . '</a></li>';
}
I would suggest you to use a counter.. Not sure if this is the right way to do it..
Change your foreach
as follows
$i=0;
foreach($categories as $category) {
if($i==0)
echo '<li class="selected"><a data-content="' . $category->slug . '" href="#' . $category->slug . '">' . $category->name . '</a></li>';
else
echo '<li><a data-content="' . $category->slug . '" href="#' . $category->slug . '">' . $category->name . '</a></li>';
$i++;
}
OR
As suggested in the answer here, you could use array_shift()
to process the first item in the array separatley.
That is, do it as below
$first = array_shift($categories);
echo '<li class="selected"><a data-content="' . $first ->slug . '" href="#' . $first ->slug . '">' . $first ->name . '</a></li>';
foreach($categories as $category) {
echo '<li><a data-content="' . $category->slug . '" href="#' . $category->slug . '">' . $category->name . '</a></li>';
}
Read more about array_shift()
in the docs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With