I’ve written before about using native WordPress functions instead of the built-in helper functions when building custom content with ACF. This is an example of using an ACF gallery field and the Backstretch.js script to create a really simple background slideshow.
The method below assumes you’re doing as I do, and concatenating all of your JS dependencies into a single file (in this case enqueued with the handle project
) and that one of these dependencies is the Backstretch.js script.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_action( 'genesis_after_header', __NAMESPACE__ . '\\output_slider' ); | |
/** | |
* Output our slider component after the header. | |
* | |
* @since 1.0.0 | |
*/ | |
function output_slider() { | |
$post_id = get_the_ID(); | |
$image_ids = get_post_meta( $post_id, 'project_header_slider', true ); | |
$slide_urls = []; | |
foreach ( $image_ids as $image_id ) { | |
$slide_urls[] = wp_get_attachment_image_url( $image_id, 'large' ); | |
} | |
// Pass array of slide URLs. | |
wp_localize_script( 'project', 'urls', $slide_urls ); | |
// Add short inline script to initialize Backstretch.js on .slider. | |
wp_add_inline_script( | |
'project', | |
'// <![CDATA[ | |
jQuery(\'.slider\').backstretch(urls, { duration: 6000, fade: 1000 }); | |
// ]]>' | |
); | |
do_action( 'project_before_slider' ); | |
include locate_template( 'views/slider.php' ); | |
do_action( 'project_after_slider' ); | |
} |
Of course, you’ll also need a view file to include, but this could be as basic as just an empty <div class="slider"></div>
. Add some simple styling to give the div some height, and the slider should work pretty well.
Leave a Reply