Echo Custom Taxonomy Field Values Outside the Loop

I assume you’re trying to use this when viewing a single post? For example, in single.php?

If so, you’ll need to grab the terms first, then grab your meta.

global $post;

if ( $terms = get_the_terms( $post->ID, 'game' ) ) {

    // $term = $terms[0]; // WRONG! $terms is indexed by term ID!
    $term = array_shift( $terms ); // RIGHT! Will get first term, and remove it from $terms array

    echo get_term_meta( $term->term_id, 'game_name', true );

}

UPDATE

Since the level of code has increased, you’d be much better off wrapping it in a function. Place the following in your functions.php;

/**
 * Get the game box image for a post.
 * 
 * @param int|object $post
 * @return string
 */
function get_game_box_image( $post = 0 )
{
    if ( ( !$post = get_post( $post ) ) || ( !$terms = get_the_terms( $post->ID, 'game' ) ) )
        return ''; // bail

    $term = array_shift( $terms );
    if ( $box = get_term_meta( $term->term_id, 'game_box', true ) ) {

        $rel = str_replace( content_url(), '', $box );
        if ( is_file( WP_CONTENT_DIR . "https://wordpress.stackexchange.com/" . ltrim( $rel, "https://wordpress.stackexchange.com/" ) ) )
            return '<div style="text-align: center;"><img src="' . $box . '" alt="" /></div>';
    }

    return '';
}

Then to display the game box image, call it like so;

<?php echo get_game_box_image(); ?>

You can optionally pass a post object or ID argument to the function to get a game box image for a specific post.

Leave a Comment