I am using "Categories" widget in my wordpress sidebar. I have use ACF field to choose Background color of category. Based on ACF field value I want to add unique class to anchor tag of each category.
For that I have implement following code.
function categories_list_filter ( $variable, $args ) {
$term_meta = get_term_meta( 5, 'category_background', true);
$variable = str_replace('<a ', '<a class="' . $term_meta . '-text"', $variable);
return $variable;
}
add_filter( 'wp_list_categories','categories_list_filter' );
How do I get category ID here in this filter ?
I seems that you want to get the ID which can be like this.
add_filter( 'wp_list_categories', 'custom_list_categories', 999, 2 );
function custom_list_categories( $output, $args ){
$terms = get_categories( $args );
$result = $output;
if( $terms ):
ob_start(); ?>
<?php
foreach( $terms as $term ):
$term_meta = get_term_meta( $term->term_id, 'category_background', true); ?>
<li class="cat-item cat-<?php echo $term->term_id; ?>">
<a class="<?php echo $term_meta; ?>" href="<?php echo get_term_link( $term ); ?>"><?php echo $term->name; ?></a>
</li>
<?php
endforeach; ?>
<?php
$result = ob_get_clean();
endif;
return $result;
}