WordPress – Advanced Custom Fields – Category Images wrong for Widgets

I am using Advanced Custom Fields to return the url location of Category images. Which would allow me to add the Category image before the title of the post. I have a function insert_image_before_title in my functions.php file which is referenced by a title filter (see below). So this seems to work well for posts on my main blog page or post’s detail page. As the correct image for the Category shows up in front of the title of the post. However, it doesn’t work so well for widgets. For instance the “The Latest Comments” or “Recent Posts” widgets would show the same Category image before the title even though the Category image may not be the correct one tied to the post (it appears it uses the first category image it comes across for a particular widget and shows the same image for the widget on the front end, if any Category image is tied to the post.

function insert_image_before_title( $title, $id = null ) 
{
    // load all 'category' terms for the post

    $terms = get_the_terms( get_the_ID(), 'category');

    // we will use the first term to load ACF data from

    if( !empty($terms) ) 
    {        
        $term = array_pop($terms);

        $category_icon_url = get_field('category_icon', $term );

        // do something with $custom_field

        if($category_icon_url)
        {        
            $title = '<img src="'. $category_icon_url .'" />' . $title;
        }

    }

    return $title;
}
add_filter( 'the_title', 'insert_image_before_title', 10, 2 );

Read more here: WordPress – Advanced Custom Fields – Category Images wrong for Widgets

Leave a Reply

Your email address will not be published. Required fields are marked *