Last active
July 5, 2020 21:03
-
-
Save ridinghoodmedia/646ae206cb82dcc3d05a to your computer and use it in GitHub Desktop.
Populate Envira Gallery with ACF gallery field
This file contains hidden or 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
/* | |
* Populate Envira Gallery with ACF gallery field | |
* | |
* Filters the gallery $data and replaces with the image data for our images in the ACF gallery field. | |
* | |
* @uses ACF Pro | |
* @uses Envira Gallery | |
* @param $data | |
* @param $gallery_id | |
*/ | |
function envira_acf_gallery( $data, $gallery_id ) { | |
// Target desired Envira gallery using ID | |
if ( $data[ "id" ] == 1020 ) { | |
//Setup new array to populate Envira gallery | |
$newdata = array(); | |
// Don't lose the original gallery id and configuration | |
$newdata[ "id" ] = $data[ "id" ]; | |
$newdata[ "config" ] = $data[ "config" ]; | |
if ( function_exists( 'get_field' ) ) | |
// Get array of images data from desired ACF gallery field | |
$image_ids = get_field( 'gallery_m3_gal', 'options' ); | |
// Check to make sure array has images | |
if( is_array( $image_ids ) ) { | |
// Populate the Envira gallery with meta from the ACF gallery | |
foreach( $image_ids as $image_id ) { | |
$newdata[ "gallery" ][ ( $image_id["id"] ) ][ "status" ] = 'active'; | |
$newdata[ "gallery" ][ ( $image_id["id"] ) ][ "src" ] = $image_id["url"]; | |
$newdata[ "gallery" ][ ( $image_id["id"] ) ][ "title" ] = $image_id["title"]; | |
$newdata[ "gallery" ][ ( $image_id["id"] ) ][ "link" ] = $image_id["url"]; | |
$newdata[ "gallery" ][ ( $image_id["id"] ) ][ "alt" ] = $image_id["alt"]; | |
$newdata[ "gallery" ][ ( $image_id["id"] ) ][ "thumb" ] = $image_id["sizes"]["thumbnail"]; | |
} | |
} | |
// Return the new array of images | |
return $newdata; | |
} | |
} | |
// Add new image data to the envira gallery | |
add_filter( 'envira_gallery_pre_data', 'envira_acf_gallery', 10, 2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this but I'm having trouble getting it to output anything. I've created an Envira Gallery with a single image - it doesn't matter what, correct? Saved my configuration and gotten the Envira Gallery ID which is 56 in my case.
I have a gallery field in my post called 'gallery' and there are images in it. I've updated your function with my Envira Gallery ID (56) as well as updated the
get_field()
call to grab my 'gallery' field.I'm calling the function in my single.php file but what do we supply as parameters for $data and $gallery_id? It won't run as-is without supplying those.
Or am I missing something else?
Thanks!