mfields / Taxonomy-Images

Enables WordPress users to easily associate images from the media library to categories, tags and custom taxonomies.
http://wordpress.mfields.org/plugins/taxonomy-images/
52 stars 21 forks source link

Get image by term ID #27

Open rilwis opened 10 years ago

rilwis commented 10 years ago

I want to get the image of a term (not the current queried term) to show outside the loop or taxonomy page template, like in menu, sidebar, etc. I found that there's no such filter for this purpose.

Right now, I have to use this solution, but I hope you can add the filter for getting image for a specific term in near future:

$term = get_term( $term_id, $taxonomy );
$tt_id = 0;
if ( isset( $term->term_taxonomy_id ) )
    $tt_id = (int) $term->term_taxonomy_id;

$associations = taxonomy_image_plugin_get_associations();
$image = '';
if ( isset( $associations[ $tt_id ] ) ) {
    $attachment_id = (int) $associations[ $tt_id ];
    $image = wp_get_attachment_image( $attachment_id, $size );
}
pabloselin commented 8 years ago

Thanks @rilwis for sharing the solution, it works nicely when wrapped in a function!

mmaarten commented 6 years ago

Thank you for the code.

I made a function to get the attachment id.

/**
 * Get Taxonomy Image ID
 *
 * Uses the 'Taxonomy Image' plugin.
 *
 * @param $term int|WP_Term|object
 * @param $taxonomy String Taxonomy name that $term is part of.
 * @return int|fase The attachment id on success. False when term does not exist or no image found.
 */
function my_get_taxonomy_image_id( $term, $taxonomy = '' )
{
    if ( ! function_exists( 'taxonomy_image_plugin_get_associations' ) ) 
    {
        return false;
    }

    if ( ! taxonomy_image_plugin_get_associations( $term_id ) ) 
    {
        return false;
    }

    $term = get_term( $term, $taxonomy );

    if ( ! $term || is_wp_error( $term ) ) 
    {
        return false;
    }

    $tt_id = 0;

    if ( isset( $term->term_taxonomy_id ) )
    {
        $tt_id = (int) $term->term_taxonomy_id;
    }

    $associations = taxonomy_image_plugin_get_associations();

    if ( isset( $associations[ $tt_id ] ) ) 
    {
        return (int) $associations[ $tt_id ];
    }

    return false;
}

Regards