Reputation: 53
I’m trying to get a list of categories into two columns. Each category has a custom field ("color") created with ACF. So far so good, i can get the list in a single column with this code:
<?php
$args = array( 'hide_empty' => '0');
$categories = get_categories($args);
if($categories){
echo '<div class="col"><ul class="cat-list">';
foreach($categories as $category) {
$color = get_field('color', 'category_'.$category->term_id);
echo '<li style="background-color:'.$color.'">';
echo '<a href="';
echo esc_url( get_category_link( $category->term_id ) );
echo '">';
echo $category->name;
echo '</a>';
echo '</li>';
}
echo '</ul></div>';
}
?>
Now i’m trying to get the list using wp_list_categories (tip: https://wpsquare.com/display-wordpress-categories-two-columns/). This works as a solution for the two columns issue, but with this method i can’t retrieve the value from the category custom field.
Thanks in advance.
Upvotes: 0
Views: 811
Reputation: 20737
$categories
is an array. One of the great things you can do with an array is... look how many items you have in them, and iterate over them using a simple for-loop.
<?php
$args = array( 'hide_empty' => '0');
$categories = get_categories($args);
if(!empty($categories)) {
$last_category_nr = count($categories) - 1;
$last_in_first_column = ceil($last_category_nr / 2);
?>
<div class="col">
<ul class="cat-list">
<?php
for ($i = 0; $i <= $last_in_first_column; $i++) {
$category = $categories[$i];
$color = get_field('color', $category);
$link = esc_url( get_category_link( $category->term_id ) );
$name = $category->name;
?>
<li style="background-color: <?php echo $color; ?>">
<a href="<?php echo $link; ?>">
<?php echo $name; ?>
</a>
</li>
<?php
}
?>
</ul>
</div>
<div class="col">
<ul class="cat-list">
<?php
for ($i = $last_in_first_column + 1; $i <= $last_category_nr; $i++) {
$category = $categories[$i];
$color = get_field('color', $category);
$link = esc_url( get_category_link( $category->term_id ) );
$name = $category->name;
?>
<li style="background-color: <?php echo $color; ?>">
<a href="<?php echo $link; ?>">
<?php echo $name; ?>
</a>
</li>
<?php
}
?>
</ul>
</div>
}
?>
Upvotes: 2