Skip to content

Instantly share code, notes, and snippets.

@jetsloth
Created October 27, 2020 22:34
Show Gist options
  • Save jetsloth/9b716e053877c0368dce5e8f8938f5e8 to your computer and use it in GitHub Desktop.
Save jetsloth/9b716e053877c0368dce5e8f8938f5e8 to your computer and use it in GitHub Desktop.
Filter Gravity Wiz Populate Anything to add Image Choices from post featured image
<?php
add_filter( "gppa_input_choices", "gppa_populate_featured_image_choices", 100, 3 );
function gppa_populate_featured_image_choices( $choices, $field, $objects ) {
if ( ! property_exists($field, 'imageChoices_enableImages') || ! $field->imageChoices_enableImages ) {
return $choices;
}
$i = 0;
foreach( $choices as &$choice ) {
$post_object = $objects[$i];
$post_id = $post_object->ID;
if ( !has_post_thumbnail($post_id) ) {
continue;
}
$choice['imageChoices_image'] = get_the_post_thumbnail_url( $post_id, "small" );
$choice['imageChoices_imageID'] = get_post_thumbnail_id( $post_id );
$i++;
}
return $choices;
}
@KZeni
Copy link

KZeni commented Jan 19, 2021

A good point, for sure. I trust your assessment of things, and matching the same methodology Gravity Wiz uses with plugins & snippets does make some sense in cases like this (wanting to avoid a bunch of unnecessary settings, having an overly-complex filter structure, etc.)

Thanks for the quick response!

@batonac
Copy link

batonac commented Mar 17, 2021

I've successfully modified this to work with an ACF image field (in this case 'front_image') as well:

add_filter( 'gppa_input_choices',  'gppa_populate_featured_image_choices', 100, 3 );

function gppa_populate_featured_image_choices( $choices, $field, $objects ) {

	if ( ! property_exists($field, 'imageChoices_enableImages') || ! $field->imageChoices_enableImages ) {
		return $choices;
	}
	
	$i = 0;
	foreach( $choices as &$choice ) {
		$post_object = $objects[$i];

		$post_id = $post_object->ID;

		$front_photo = get_field( 'front_photo', $post_id );

		if ( $front_photo ) {
			$choice['imageChoices_image'] = $front_photo['sizes']['thumbnail'];
			$choice['imageChoices_imageID'] = $front_photo['id'];
		}
		$i++;
	}

	return $choices;

}

@jetsloth
Copy link
Author

jetsloth commented Mar 17, 2021 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment