Home Forums General Issues Category Images wrong for Widgets


Category Images wrong for Widgets

  • I am using ACF to store the url location of the Category image. I am adding 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 tied to the post (it appears it uses the first category image it comes across for a particular widget and shows the same image if the post had a Category image assigned to it.

    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
                $title = '<img src="'. $category_icon_url .'" />' . $title;
        return $title;
    add_filter( 'the_title', 'insert_image_before_title', 10, 2 );
Viewing 1 post (of 1 total)

The topic ‘Category Images wrong for Widgets’ is closed to new replies.