对自定义字段使用自定义分类术语 ID


Using Custom Taxonomy Term ID for Custom Field

我已经为我的讲道自定义帖子类型创建了一个自定义的单讲道.php模板文件,并希望包含这篇文章的讲道演讲者的图像自定义字段。

自定义分类 ID:sermon_speaker自定义字段 ID:sermon_speaker_image

我已经能够使用以下方法将分类术语 ID 显示为页面上的数字:

<?php
$terms = wp_get_post_terms($post->ID, "sermon_speaker");
foreach ($terms as $termid) {  
echo $termid->term_id;
} 
?>

正在尝试弄清楚如何在我目前拥有 . $term_id 的代码中如何使用这个术语 ID,以便它将术语 ID 添加到背景图像 URL 的末尾。

<div class="sermon-speaker-image" style="background-image: url('<?php the_field( 'sermon_speaker_image', 'sermon_speaker_' . $term_id ); ?>');"></div>

更新:以下代码是基于以下答案的工作解决方案:

<?php
global $post;
// load all 'sermon_speaker' terms for the post
$terms = get_the_terms($post->ID, 'sermon_speaker');
// we will use the first term to load ACF data from
if( !empty($terms) )
{
    $term = array_pop($terms);
    $custom_field = get_field('sermon_speaker_image', $term );
}
?>
<div class="sermon-speaker-image" style="background-image: url('<?php echo $custom_field; ?>');"></div>

试试这段代码,这应该适合你

 global $post;
    // load all 'sermon_speaker' terms for the post
    $terms = get_the_terms($post->ID, 'sermon_speaker');
    // we will use the first term to load ACF data from
    if( !empty($terms) )
    {
        $term = array_pop($terms);
        $custom_field = get_field('sermon_speaker_image', $term );
        // do something with $custom_field
        //i.e. echo $custom_field;
        //i.e. echo "<img src='$custom_field'/>";
       ?>
<div class="sermon-speaker-image" style="background-image: url('<?php echo $custom_field; ?>');"></div>
<?
    }

您可以阅读有关高级自定义字段的官方文档的更多信息

两个想法:

第一个

<div class="sermon-speaker-image" style="background-image: url('<?php the_field( 'sermon_speaker_image', 'sermon_speaker_' ?> . <?php echo $term_id ?> ); ?>');"></div>

我使用回声来实际显示它。

第二个

这是我最喜欢的,也是实际工作的一个。您可以使用 jQuery 将属性背景图像设置在所需的位置,并从自定义类型追加值。

$(document).ready(function() {
     var new_link = $(".sermon-speaker-image").attr("background-image");   
     new_link = x.append('<?php echo $term_id; ?>','');
     jQuery(".sermon-speaker-image").attr("background-image", new_link);
}

当然,您必须检查(url=url+id)图像是否确实存在。