Using a custom taxonomy identifier for a custom field

I created a custom single-sermons.php template file for the type of custom messages of my sermons, and I want to include a custom field in this message for the speaker to preach for this message.

Custom Taxonomy ID: sermon_speaker Custom Field ID: sermon_speaker_image

I got a taxonomy term identifier that will display as a page number using:

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

I am trying to figure out how to use this term identifier in the code below, where I am now. $ term_id to add a term identifier to the end of the background image URL.

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

Update: The following code is a working solution based on the answer below:

 <?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> 
+5
source share
2 answers

Try this code, this should work for you

  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 //ie echo $custom_field; //ie echo "<img src='$custom_field'/>"; ?> <div class="sermon-speaker-image" style="background-image: url('<?php echo $custom_field; ?>');"></div> <? } 

Read more about the official documentation of additional custom fields

+2
source

Two thoughts:

First one

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

I use echo to display it.

Second option

This is my favorite and really working. You can use jQuery to set the attribute's background image wherever you want and add a value from a custom type.

 $(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); } 

Of course, you should check that the image (url = url + id) really exists.

0
source

Source: https://habr.com/ru/post/1209830/


All Articles