Wordpress - 高级自定义字段 - 窗口小部件的类别图像错误

时间:2017-04-25 18:58:58

标签: wordpress image advanced-custom-fields taxonomy-terms

我正在使用高级自定义字段来返回类别图像的网址位置。这将允许我在帖子的标题之前添加类别图像。我的functions.php文件中有一个函数insert_image_before_title,它由标题过滤器引用(见下文)。所以这似乎适用于我的主要博客页面或帖子的详细信息页面上的帖子。由于类别的正确图像显示在帖子的标题前面。但是,对于小部件来说,它不能很好地工作。例如,“最新评论”或“最近帖子”小部件将在标题之前显示相同的类别图像,即使类别图像可能不是与帖子绑定的正确图像(它似乎使用它遇到的第一个类别图像对于特定小部件,如果任何类别图像与帖子绑定,则在前端显示小部件的相同图像。

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 );

1 个答案:

答案 0 :(得分:1)

Try this:
<?php
$args = array(
    'taxonomy' => 'post_tag',
    'hide_empty' => true,
);
$terms = get_terms( $args );
foreach ($terms as $term):
$thumbnail = get_field('field_name', $term->taxonomy . '_' . $term->term_id);
?>
<!--If an array is returned in ACF-->
<img src="<?php echo $thumbnail['url'];?>" alt="<?php echo $thumbnail['title'];?>">
<!--If an url is returned in ACF-->
<img src="<?php echo $thumbnail;?>" alt="#">
<?php endforeach; ?>