I'm using ACF and I have a color picker field the_field('marker)
in taxonomy page project-cat
to let client to select color for each category. I want to display each category color for related posts as well.
This code shows how I display color for each category which is fine:
<?php
$terms = get_terms( 'project-cat' );
// var_dump($terms);
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
foreach ( $terms as $term ) {
?>
<li>
<input id="category_<?php echo $term->term_id; ?>" type="checkbox" name="categories" value="<?php echo $term->term_id; ?>" checked="checked" disabled>
<label for="category_<?php echo $term->term_id; ?>">
<div class="catCircle" style="background-color:<?php $marker = get_field('marker', $term->taxonomy . '_' . $term->term_id); echo $marker; ?>"></div>
<?php echo $term->name; ?>
</label>
</li>
<?php
}
?>
<?php
}
?>
And this is my array for posts :
<?php
$args = array(
'post_type' => 'project',
'posts_per_page' => -1,
);
$posts_array = get_posts($args);
foreach($posts_array as $post){
$post=(array)$post;
$location = get_field('google_map',$post['ID']);
$term = get_terms( 'project-cat' );
$array[] = array(
'title' => $post['post_title'],
'subtitle' => get_field('status',$post['ID']),
'catColor' => get_field('marker', $term->taxonomy . '_' . $term->term_id),
'catID' => get_field('taxo',$post['ID']),
'lat' => $location['lat'],
'lng' => $location['lng'],
'url' =>get_permalink($post['ID']),
);
}
?>
This code displays one of my category colors for all posts. eg: category A , selected color is pink, all posts shows pink color.
if anyone could help me with correcting the query would be appreciated.
I'd go for something like this, having a default color (in my example #ff0000) and then overriding that with the color of the first category of the post. Notice that I'm using wp_get_post_terms - I suppose that is what you want, not get_terms (which will always get ALL the terms, not just those that are selected for the individual post).
$terms = wp_get_post_terms( $post['ID'], 'project-cat' );
$catColor = "#ff0000";
if(is_array($terms) && count($terms)) {
if($newColor = get_field('marker', $terms[0]->taxonomy . '_' . $terms[0]->term_id)) {
$catColor = $newColor;
}
}
$array[] = array(
'title' => $post['post_title'],
'subtitle' => get_field('status',$post['ID']),
'catColor' => $catColor,
'catID' => get_field('taxo',$post['ID']),
'lat' => $location['lat'],
'lng' => $location['lng'],
'url' =>get_permalink($post['ID']),
);