You would use the code on your (archive) template file, which you use to display the custom posts. On the template the code would be placed within the Loop.
For example you could have a custom post type specific archive file for this (more on Template Hierarchy).
// archive-$posttype.php
while ( have_posts() ) :
the_post();
$statuses = wpse_410403_status_terms( get_the_ID() );
?>
<div class="entry">
<h2><?php the_title(); ?></h2>
<div class="sp-pcp-post-meta">
<?php
if ( $statuses ) {
foreach ($statuses as $status) {
echo wpse_410403_status_html($status);
}
}
?>
</div>
</div>
<?php
endwhile;
I would recommend using helper functions, placed in your theme’s functions.php
file, for retrieving the terms and their meta data to keep your template file cleaner and making it easier to maintain your codebase.
In my example above I’ve used a helper function to retrieve the post’s custom taxonomy terms. This is to force the result to be always an array
as get_the_terms()
returns false
or WP_Error
in some cases.
function wpse_410403_status_terms( int $post_id ) : array {
$terms = get_the_terms( $post_id, 'status' );
return $terms && is_array($terms) ? $terms : [];
}
For retrieving the color value you can have another function. This way you can protect your site from the situation when ACF is not active and it’s get_field()
function is not available. If that happens you can fallback to WP’s native get_term_meta()
function to retrieve the stored color value from the term meta (which ACF also does after jumping through few hoops).
function wpse_410403_status_color( WP_Term $term ) : string {
return function_exists('get_field')
? get_field( 'bpn_statuscolor', $term )
: get_term_meta( 'bpn_statuscolor', $term->term_id, true ); // check that the meta key is correct and matches the way ACF stores the data
}
Then a third function, for rendering the status terms with background color, for reusability.
function wpse_410403_status_html( WP_Term $term ) : string {
return sprintf(
'<span class="status" style="background-color: %s;">%s</span>',
sanitize_hex_color(
wpse_410403_status_color( $term )
),
esc_html( $term->name )
);
}
And of course, you can always wrap all three functions into a single function for even cleaner template usage.
function wpse_410403_statuses( int $post_id ) : string {
$statuses = wpse_410403_status_terms( $post_id );
return $statuses
? implode( '', array_map( 'wpse_410403_status_html', $statuses ) )
: '';
}
I.e.
while ( have_posts() ) :
the_post();
?>
<div class="entry">
<h2><?php the_title(); ?></h2>
<div class="sp-pcp-post-meta">
<?php echo wpse_410403_statuses( get_the_ID() ); ?>
</div>
</div>
<?php
endwhile;