首页 文章

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

提问于
浏览
5

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

  • 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上阅读更多内容

  • 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)图像是否确实存在 .

相关问题