0

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..

1

You 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.
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.