I am trying to implement a way of having different colours for different categories in single.php. So, I have created a colour Picker field with Advanced Custom Fields and this field shows on each category page. Then the end user can choose a colour for each category in each category page where this colour picker field is present. After that the only thing I want to get the colours the end user chooses are the category links on my single.php.
At the moment I have it working fine if I only have one category. However, when I assign more than one category to the post they all become the same colour as the last category assigned.
Here is my code:
$terms = get_the_terms( get_the_ID(), 'category');
if( !empty($terms) ) {
$term = array_shift($terms);
$category_color = get_field('category_color', $term );
}
$post_categories = get_the_category();
$separator = ' ';
$output = '';
if ( $post_categories ) {
foreach( $post_categories as $post_category ) {
$output .= '<li class="meta-category">';
$output .= '<a style="color:' . $category_color . ';" href="' . esc_url( get_category_link( $post_category->term_id ) ) . '" alt="' . esc_attr( sprintf( __( 'View all posts in %s', 'mytheme' ), $post_category->name ) ) . '">' . esc_html( $post_category->name ) . '</a>' . $separator;
$output .= '</li>';
}
echo trim( $output, $separator );
}
And to illustrate better the problem I am facing here are some images of my entry categories on my single.php:
Image 1 - Here I have the aciform category, for example, which has been assigned the font colour of red. On its own it is red as it should be
Image 2 - Here I have the beauty category, for example, which has been assigned the font colour of blue. On its own it is blue as it should be
Image 3 - And here I have assigned those two categories to the same post. And the expected result should be Aciform - red and Beauty - blue. But for some reason they both show as blue..
I have been struggling with this for awhile and can't seem to find a solution. I guess it might even be something really simple I am missing but after so much time I just can't see it.
$category_color
in your output ( loop ) is an array. You need to define them.