我已经为我的布道自定义帖子类型创建了一个自定义的单个sermons.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;
}
?>
我正在尝试弄清楚如何在我目前拥有的代码中使用此术语ID . $ term_id,以便将术语ID添加到背景图像URL的末尾 .
<div class="sermon-speaker-image" style="background-image: url('<?php the_field( 'sermon_speaker_image', 'sermon_speaker_' . $term_id ); ?>');"></div>
Update: 以下代码是基于以下答案的可行解决方案:
<?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>
2 回答
试试这个应该适合您的代码
你可以在official documentation of Advanced custom fields上阅读更多内容
两个想法:
第一个
我用echo实际显示它 .
第二个
这是我最喜欢的,实际上是一个 . 您可以使用jQuery在所需的位置设置属性background-image,并附加自定义类型的值 .
当然,你必须检查(url = url id)图像是否确实存在 .