acf_field_image::format_value_for_jsonldpublicACF 6.8.0

Formats the field value for JSON-LD output.

Method of the class: acf_field_image{}

No Hooks.

Returns

Mixed.

Usage

$acf_field_image = new acf_field_image();
$acf_field_image->format_value_for_jsonld( $value, $post_id, $field );
$value(mixed) (required)
The value of the field.
$post_id(int|string) (required)
The ID of the post.
$field(array) (required)
The field array.

Changelog

Since 6.8.0 Introduced.

acf_field_image::format_value_for_jsonld() code ACF 6.8.8

public function format_value_for_jsonld( $value, $post_id, $field ) {
	if ( empty( $value ) ) {
		return null;
	}

	// Get output format with fallback.
	$output_format = $field['schema_output_format'] ?? '';
	if ( empty( $output_format ) ) {
		$property      = $field['schema_property'] ?? '';
		$output_format = \ACF\AI\GEO\Schema::get_default_output_format( $this->name, $property );
	}

	// Get the attachment ID.
	$attachment_id = is_array( $value ) ? ( $value['ID'] ?? 0 ) : (int) $value;
	if ( ! $attachment_id ) {
		return null;
	}

	$url = wp_get_attachment_url( $attachment_id );
	if ( ! $url ) {
		return null;
	}

	// URL format - just return the URL string.
	if ( 'URL' === $output_format ) {
		return $url;
	}

	// ImageObject format - return structured object.
	$image_object = array(
		'@type' => 'ImageObject',
		'url'   => $url,
	);

	// Add dimensions if available.
	$metadata = wp_get_attachment_metadata( $attachment_id );
	if ( ! empty( $metadata['width'] ) ) {
		$image_object['width'] = (int) $metadata['width'];
	}
	if ( ! empty( $metadata['height'] ) ) {
		$image_object['height'] = (int) $metadata['height'];
	}

	// Add caption/alt text if available.
	$alt = get_post_meta( $attachment_id, '_wp_attachment_image_alt', true );
	if ( $alt ) {
		$image_object['caption'] = $alt;
	}

	// Add name from attachment title.
	$attachment = get_post( $attachment_id );
	if ( $attachment && $attachment->post_title ) {
		$image_object['name'] = $attachment->post_title;
	}

	return $image_object;
}