[]]),
];
}
public function sanitizeValue($value, array $field)
{
// The id of an attachment. Anything else (an id that is gone, text) becomes empty, without a PHP warning.
$meta = get_post_meta((int) $value);
if (! empty($meta['_wp_attachment_metadata']) || ! empty($meta['_wp_attached_file'])) {
return $value;
}
return '';
}
public function usesAssets(): bool
{
return true;
}
public function enqueue(array $field): void
{
wp_enqueue_media();
// Versioned by file date (like ColorPicker), not by the plugin version: a changed script under an
// unchanged plugin version would otherwise keep being served from the browser cache.
wp_enqueue_script(
Plugin::PREFIX . 'media-js',
Plugin::assetsUrl() . 'js/' . Plugin::PREFIX . 'media.js',
['wp-i18n'],
Enqueue::version('js/' . Plugin::PREFIX . 'media.js'),
'all'
);
Enqueue::scriptTranslations(Plugin::PREFIX . 'media-js');
wp_enqueue_style(
Plugin::PREFIX . 'media-css',
Plugin::assetsUrl() . 'css/' . Plugin::PREFIX . 'media.css',
[],
Enqueue::version('css/' . Plugin::PREFIX . 'media.css'),
'all'
);
}
/**
* The image (`` with srcset), in the size of `size="..."` (default: full).
*/
public function displayValue($value, array $field, array $args): string
{
$id = Display::attachmentId($value);
if ($id === 0) {
return '';
}
return (string) wp_get_attachment_image($id, ($args['size'] ?? '') !== '' ? (string) $args['size'] : 'full');
}
public function bindingValue($value, array $field, string $attribute): ?string
{
$id = Display::attachmentId($value);
if ($id === 0) {
return null;
}
switch ($attribute) {
case 'url':
return (string) wp_get_attachment_image_url($id, 'full');
case 'alt':
return (string) get_post_meta($id, '_wp_attachment_image_alt', true);
case 'title':
return get_the_title($id);
case 'id':
return (string) $id;
case 'content':
case 'text':
return $this->displayValue($value, $field, []);
}
return null;
}
public function render(array $field, $value): void
{
printf('