使用自定义分类术语标识自定义字段

时间:2014-12-24 11:29:41

标签: php wordpress custom-fields advanced-custom-fields custom-taxonomy

我已经为我的讲道自定义帖子类型创建了一个自定义的单个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>

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

<?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 个答案:

答案 0 :(得分:2)

试试这个应该适用的代码

 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>
<?
    }

您可以在official documentation of Advanced custom fields

上阅读更多内容

答案 1 :(得分:0)

两个想法:

第一个

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

我使用echo实际显示它。

第二个

这是我最喜欢的,实际上是一个。 您可以使用jQuery在所需的位置设置属性background-image,并附加自定义类型的值。

$(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)图像是否确实存在。

相关问题