I have custom field in posts called hex_colors which contains hex color codes separated with white space, custom field value is like this:
"000000 f0f0f0 c0c0c0 202020 404040 "
I can change function which create it to separate with ", " or " | " or anything else, if it helps.
I can show it like this:
<?php
if (get_custom_field('hex_colors')) {
echo '<div>'; echo get_custom_field('hex_colors'); echo '</div>';
}
?>
But I would like to show each color code one by one and to style each one, for example instead of this:
<div>000000 f0f0f0 c0c0c0 202020 404040</div>
to get something like this:
<div class="colors" style="background-color:#000000">000000</div>
<div class="colors" style="background-color:#f0f0f0">f0f0f0</div>
<div class="colors" style="background-color:#c0c0c0">c0c0c0</div>
<div class="colors" style="background-color:#202020">202020</div>
<div class="colors" style="background-color:#404040">404040</div>
I tried like this:
if ( get_post_meta( get_the_ID(), 'hex_colors', true ) ){
$colors = get_post_meta( get_the_ID(), 'hex_colors', true );
$colors = explode( ' ' , $colors );
foreach( $colors as $color ) {
echo '<div>';
echo $color;
echo '</div>';
}
}
It works, but I get output something like this:
<div>000000</div>
<div></div>
<div>f0f0f0</div>
<div></div>
<div>c0c0c0</div>
<div></div>
<div>c0c0c0</div>
<div></div>
<div>404040</div>
<div></div>
Empty div () at the end (because of " " white space at the end of custom field value. This is function which create custom filed:
<?php
for ($i = 0; $i < $colors_to_show; $i += $inc) {
for($j=0;$j<$inc;$j++) {
$out_color_text .= ''.$colors_key[$i + $j].' '; // CUSTOM FIELD VALUE
}
}
$id = $post->ID; // Post ID
$value = $out_color_text;
add_post_meta($id, 'hex_colors', $value, true);
?>
Some fix to create value without white space at the end?
explode()
andarray_unique()
.explode
call, try using two spaces as the delimiter instead a single spacetrim( $colors )
before exploding it.