I added custom image and icon to my custom taxonomy, and I know how to display it in the front end in the taxonomy template page.
$headImageId = get_term_meta( get_queried_object_id(), 'category-image', true );
$headImageUrl = ( ( $headImageId != '' ) ? wp_get_attachment_url( $headImageId ) : '' );
But how do I call it in my single post template? I want to use the image from the taxonomy term the custom post belongs to as a header background. I can't get my head around this..
I added custom image and icon to my custom taxonomy, and I know how to display it in the front end in the taxonomy template page.
$headImageId = get_term_meta( get_queried_object_id(), 'category-image', true );
$headImageUrl = ( ( $headImageId != '' ) ? wp_get_attachment_url( $headImageId ) : '' );
But how do I call it in my single post template? I want to use the image from the taxonomy term the custom post belongs to as a header background. I can't get my head around this..
Share Improve this question asked Jun 11, 2020 at 1:17 artist learning to codeartist learning to code 3311 gold badge5 silver badges18 bronze badges1 Answer
Reset to default 1You will need to use get_the_terms()
to get the taxonomy terms associated with the post and loop through them until you find one that has an image set:
$post. = get_queried_object();
$terms. = get_the_terms( $post, 'taxonomy_name_here' );
$image_url = null;
if ( $terms && ! is_wp_error( $terms ) ) {
foreach ( $terms as $term ) {
$attachment_id = get_term_meta( $term->term_id, 'category-image', true );
if ( $attachment_id ) {
$image_url = wp_get_attachment_image_url( $attachment_id, 'full' );
break;
}
}
}
if ( $image_url ) {
// Output image as needed.
}