wp-rest-blocks icon indicating copy to clipboard operation
wp-rest-blocks copied to clipboard

Support for ACF image field return format

Open raidoa opened this issue 3 years ago • 3 comments
trafficstars

Hi!

When creating an image field with ACF, wp-rest-blocks does not seem to respect the chosen return format in the ACF field settings. When I choose "Image URL" or "Image Array", it still returns Image ID in the API.

Chosen settings for the field: Screenshot 2022-01-26 at 11 08 27

Output in the API: Screenshot 2022-01-26 at 11 12 27

Not even sure if wp-rest-blocks should respect those settings or is it the responsibility of the ACF plugin instead?

raidoa avatar Jan 26 '22 11:01 raidoa

Same problem, i think that this is an important tasks, it doesn't support any image return format.

marcokumanaku avatar Jun 01 '22 11:06 marcokumanaku

Hello @raidoa Did you get any solutions for image I am also struggling with the things. Please let me know If you have found any solutions.

sunilsingh2019 avatar Jun 01 '23 01:06 sunilsingh2019

I am not an expert on Wordpress, PHP, ACF or Gutenberg, but I ran into this problem and was able to add support for this to the library. I added an else on line 67 of data.php, so the full if-statement now reads:

if ( ! isset( $attr[ $key ] ) ) {
	$attr[ $key ] = get_attribute( $attribute, $block_object->inner_html, $post_id );
}else{
	if($key == 'data'){
		foreach ( $attr[$key] as $dataKey => $dataAttribute ) {
			if($dataKey[0] != '_' && gettype($dataAttribute) == 'integer' && str_contains($dataKey, 'image')){
				$attr[$key][$dataKey] = array('url' => wp_get_original_image_url($dataAttribute), 'alt' => get_post_meta($dataAttribute, '_wp_attachment_image_alt', TRUE));
			}
		}
	}
}

This causes the api to return something like:

"hero_image":
 {
	"url": "http:\/\/localhost\/wp-content\/uploads\/2023\/06\/1a.png",
	"alt": "This is alt text."
},

instead of hero_image: 6.

The big caveat here is that as far as I could find, there was no obvious way to tell the intended type of an ACF field, so I can't tell the difference between something intended to be an integer and something intended to be a picture. Thus, I try to make an integer into an image object only if the variable name doesn't start with an underscore and it has "image" in the variable name.

Obviously, that is not a foolproof system, but it was the best thing I could come up with, and works well enough to make the system usable. If anyone does know how to tell the intended datatype of an ACF field, please let us know because that would be much less prone to user error.

I've attached my version of data.php for reference. data.txt

dexo568 avatar Jun 19 '23 18:06 dexo568