문제

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

도움이 되었습니까?

해결책

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.
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 wordpress.stackexchange
scroll top