I added a Text field to the Category taxonomy using ACF so that I can add a font awesome icon code to be displayed in a list of all categories.
The end result I am looking for is a list of all categories names linked to their respective category pages (if they have posts or not) with the icon from the custom field before each category name.
Reviewing the ACF documents and looking around for a solution I have only been able to display one icon at a time or just create errors.
Is there a more straight forward way I can loop through all of the categories and include the name, link and icon from my ACF custom field in the way I would do so for posts that have a custom field added on to it?
Here is the code I have so far but it only shows one at a time even though I am trying to use a foreach to loop through them all:
<?php
$categories = get_the_category();
$separator = ' ';
$output = '';
foreach( $categories as $category ) {
$terms = get_the_terms( get_the_ID(), 'category');
if($terms) {
$term = array_pop($terms);
$icon = get_field('cat_icon', $term );
}
echo $icon;
$output .= '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '" alt="' . esc_attr( sprintf( __( 'View all posts in %s', 'textdomain' ), $category->name ) ) . '">' . esc_html( $category->name ) . '</a>' . $separator;
}
echo trim( $output, $separator ); ?>
Any help is appreciated, thank you!
As requested here is a screenshot, you can see it is displaying the icon from my custom field but only one category out of the 3 I currently have added.
CodePudding user response:
You can use get_terms
. try the below code.
<?php
$categories = get_terms( array(
'taxonomy' => 'category',
'hide_empty' => false
) );
$separator = ' ';
$output = '';
foreach( $categories as $category ) {
if($category) {
$icon = get_field('cat_icon', $category );
}
echo $icon;
$output .= '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '" alt="' . esc_attr( sprintf( __( 'View all posts in %s', 'textdomain' ), $category->name ) ) . '">' . esc_html( $category->name ) . '</a>' . $separator;
}
echo trim( $output, $separator );
?>