Archived topic
Need to use custom field in header element
3 replies · Started by _blank on May 17, 2022
I created a custom header element with a video background using this article as a starting point.
I used ACF to create a custom field named home_page_hero_video that returns the video url so the client can change it.
I've tried using {{custom_field.home_page_hero_video}} and using shortcodes as described here and here but I haven't been able to get it to work.
Using src="{{custom_field.home_page_hero_video}}" in the header HTML results in src(unknown) in the browser. When I try a shortcode it outputs in the browser exactly as I enter it in the header HTML. For example src="[shortcode_name]".
Suggestions?
Hi Paul,
Try this PHP snippet to create a shortcode that includes the ACF field, change bg-video-url and bg-img-url to match the video URL/poster URL's ACF field name. Use[hero_video] as the shortcode.
You can also use this shortcode in a block element.
add_shortcode( 'hero_video', function() {
ob_start();
$video_link = get_field('bg-video-url');
$poster_link = get_field('bg-img-url');
echo '<video loop muted autoplay playsinline poster="'.$poster_link.'" class="background-video">
<source src="'.$video_link.'" type="video/mp4">
</video>
<div class="background-video-content">
Your Element content in here.
</div>';
return ob_get_clean();
} );
Hi Ying, I ended up needing to add the post ID to get_field, like this: $video_link = get_field('home_page_hero_video', 5851); but it works.
Thank you!
No problem :)