In a plugin I'm building, I've added a field named attribution
to attachments via the attachment_fields_to_edit
filter.
I'm trying to get this info in the block editor but when I output the variable holding the attachments using console.log
, I only see the following props. This is an example:
alt: ""
caption: ""
id: 25
link: "http://example.com/page/1_58image1600x1200/"
mime: "image/jpeg"
sizes: Object { thumbnail: {…}, medium: {…}, large: {…}, … }
subtype: "jpeg"
type: "image"
url: "http://example.com/wp-content/uploads/2023/07/1_58image1600x1200.jpg"
Is there a way to get the data from attachment fields added via the attachment_fields_to_edit
filter in Gutenberg?
UPDATE (Adding some code for completeness):
This is the component that opens a window for selecting attachments:
<MediaPlaceholder
accept="image/*"
allowedTypes={['image']}
onSelect={setItems}
multiple={true}
gallery={true}
addToGallery={true}
handleUpload={true}
labels={
{ title: __('My Gallery') }
}
/>
This is the function that stores the selected attachments in an array attribute named items
:
const setItems = (media) => {
setAttributes({ items: media })
}
This is the function that displays the stored attachments in the items
attribute:
const displayItems = (items) => {
console.log(items);
return (
items.map((item, index) => {
return (
<div className="attachment" key={index}>
<figure>
<img src={item.url} alt={item.alt} key={item.id} />
</figure>
</div>
)
})
)
};
The console.log(items)
call just returns an array of attachments without the custom attribution
field.
As suggested, I registered the meta field using the register_post_meta
function in the PHP side with no success:
function register_meta_field() {
register_post_meta(
'attachment',
'attribution',
array(
'show_in_rest' => true,
'type' => 'string',
'single' => true,
'sanitize_callback' => 'sanitize_text_field',
'auth_callback' => function() {
return current_user_can( 'edit_posts' );
},
)
);
}
add_action( 'init', 'register_meta_field' );
show_in_rest
totrue
?/wp-json/wp/v2/media/25
) Also, how are you getting the data in the block editor? What's your code?/wp-json/wp/v2/media
directly, I get ALL the attachment data. It seems that theMediaPlaceholder
component is the culprit, as it only returns a reduced version of this data with just the main attachment fields.