Created
November 20, 2015 23:46
-
-
Save JohnBunka/6311137de0ca4552b126 to your computer and use it in GitHub Desktop.
Display Advanced Custom Fields (ACF) in an Envira Gallery. From http://www.jowaltham.com/display-advanced-custom-fields-envira-gallery/
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 | |
// Do NOT include the opening php tag above | |
add_action( 'genesis_entry_content', 'jmw_add_envira_gallery_after_content', 15 ); | |
/* | |
* Add the gallery after the end of the content | |
*/ | |
function jmw_add_envira_gallery_after_content() { | |
$gallery = get_post_meta( get_the_ID(), 'gallery' ); // 'gallery' is name of my ACF gallery field | |
// If we have something output the gallery | |
if( is_array( $gallery[0] )) { | |
if( shortcode_exists( 'envira-gallery' )) { | |
echo do_shortcode( '[envira-gallery id="107"]' ); | |
} | |
else { // Fall back to WordPress inbuilt gallery | |
$image_ids = $gallery[0]; | |
$shortcode = '[gallery ids="' . implode( ',', $image_ids ) . '"]'; | |
echo do_shortcode( $shortcode ); | |
} | |
} | |
} | |
add_filter( 'envira_gallery_pre_data', 'jmw_filter_envira_gallery_data', 10, 2); | |
/* | |
* Filter the gallery $data and replace with the image data for our images in the ACF gallery field | |
*/ | |
function jmw_filter_envira_gallery_data( $data, $gallery_id ) { | |
$newdata = array(); | |
// Don't lose the original gallery id and configuration | |
$newdata[ "id" ] = $data[ "id" ]; | |
$newdata[ "config" ] = $data[ "config" ]; | |
// Get list of images from our ACF gallery field | |
$gallery = get_post_meta( get_the_ID(), 'gallery' ); | |
$image_ids = $gallery[0]; // It's an array within an array | |
// If we have some images loop around and populate a new data array | |
if( is_array( $image_ids ) ) { | |
foreach( $image_ids as $image_id ) { | |
$newdata[ "gallery" ][ $image_id ][ "status" ] = 'active'; | |
$newdata[ "gallery" ][ $image_id ][ "src" ] = esc_url( wp_get_attachment_url( $image_id ) ); | |
$newdata[ "gallery" ][ $image_id ][ "title" ] = esc_html( get_the_title( $image_id ) ); | |
$newdata[ "gallery" ][ $image_id ][ "link" ] = esc_url( wp_get_attachment_url( $image_id ) ); | |
$newdata[ "gallery" ][ $image_id ][ "alt" ] = trim(strip_tags( get_post_meta($image_id, '_wp_attachment_image_alt', true) )); | |
$newdata[ "gallery" ][ $image_id ][ "thumb" ] = esc_url( wp_get_attachment_thumb_url( $image_id ) ); | |
} | |
} | |
return $newdata; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment