0

I have a custom taxonomy called 'game'; posts have a taxonomy value, i.e. Halo, which then has seven different fields; game_name, game_genre etc.

I'm trying to echo the meta data for a given post's custom taxonomy albeit without much luck. The small piece of PHP that I tried to use to echo the metadata for the field game_name (designed to be run in a PHP widget) doesn't appear to work. It uses a custom hook created by the plugin Simple Term Meta

<?php
global $term;
echo get_term_meta($term->ID, 'game_name', true);
?>

Any help in sorting this out would be appreciated, I didn't realise it'd be this complicated.

1 Answer 1

2

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 . '/' . ltrim( $rel, '/' ) ) )
            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.

33
  • Err no this is being used in a PHP widget in a sidebar. And unfortunately that still doesn't work :/ Mar 12, 2011 at 16:48
  • Okaay... What do you get if your printr($post); and printr($terms);? Mar 12, 2011 at 16:57
  • Fatal error: Call to undefined function printr() in /home/arranf/co-opreviews.com/wp-content/plugins/linkable-title-html-and-php-widget/linkable-title-html-and-php-widget.php(44) : eval()'d code on line 4 Mar 12, 2011 at 17:47
  • Wow, mega fail for me - should be print_r Mar 12, 2011 at 19:42
  • Ok, done the print. pastebin.com/7BibWLXY Mar 12, 2011 at 23:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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