Wordpress 在Gutenberg块的后端视图中使用附件ID属性获取附件url
如果Gutenberg块存储了附件ID属性,是否有方法使用该ID动态获取特定缩略图大小的url 属性将存储在块中,如下所示:Wordpress 在Gutenberg块的后端视图中使用附件ID属性获取附件url,wordpress,wordpress-gutenberg,gutenberg-blocks,Wordpress,Wordpress Gutenberg,Gutenberg Blocks,如果Gutenberg块存储了附件ID属性,是否有方法使用该ID动态获取特定缩略图大小的url 属性将存储在块中,如下所示: imageID: { type: 'integer', }, 这个想法是在Gutenberg编辑器视图中动态显示该图像。几周前我遇到了这个问题。这让我困惑了一段时间,但您可以使用和getMedia()来完成。在一个简单的例子中,我们必须从我们拥有的ID中获取媒体对象。查看该对象内部的缩略图对象。然后我们将获得源url属性。您的文件应类似于: // Bloc
imageID: {
type: 'integer',
},
这个想法是在Gutenberg编辑器视图中动态显示该图像。几周前我遇到了这个问题。这让我困惑了一段时间,但您可以使用和
getMedia()
来完成。在一个简单的例子中,我们必须从我们拥有的ID中获取媒体对象。查看该对象内部的缩略图对象。然后我们将获得源url
属性。您的文件应类似于:
// Block image preview
const blockEdit = createElement("div", null,
// If image defined, get the source_url
const imageThumbURL = props.imageObj ? props.imageObj.media_details.sizes.thumbnail.source_url : null
createElement("img", {
src: imageThumbURL
})
)
// Use withSelect(x)(y) to load image url on page load
const fieldData = withSelect( (select, props) => {
// Get the image ID
const imageId = props.attributes.imageID
// Create "props.imageObj"
return {
// If image defined, get the image "media" object
imageObj: imageId ? select("core").getMedia(imageId) : null
}
})(blockEdit)
wp.blocks.registerBlockType('plugin-namespace/block-name', {
attributes: {
imageID: {
type: 'Number'
}
},
edit: fieldData
}
以上内容未经测试,但我使用该解决方案允许在使用ID加载页面时加载媒体项。希望这能有所帮助