wordpress - 在 Gutenberg 块的后端视图中使用附件 ID 属性获取附件 url
问题描述
如果 Gutenberg 块存储了附件 ID 属性,是否有办法使用该 ID 动态获取特定缩略图大小的 url?
该属性将像这样存储在块中:
imageID: {
type: 'integer',
},
这个想法是在 Gutenberg 编辑器视图中动态显示该图像。
解决方案
几周前我遇到了这个问题。它让我困惑了一段时间,但你可以使用withSelect()()和getMedia()
. 简而言之,我们将不得不从我们拥有的 ID 中获取媒体对象。在该对象内部查找缩略图对象。然后我们将获得source_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 加载页面时加载。希望这会有所帮助。
推荐阅读
- webpack - SplitChunksPlugin 不为入口点之间共享的依赖项生成块
- node.js - 是否有一个属性可以知道图像在 Jimp 中是垂直还是水平?
- macos - 向 macOS 通知添加“关闭”按钮
- jquery - 将新行插入网格会导致重复行
- objective-c - Objective-C++ 中的 C++ 对象何时被销毁?
- c++ - 当初始化需要多个步骤时,初始化变量的正确方法是什么?
- python - 用于查找数字的最大素数的 python 代码问题(Project Euler 问题 3)
- r - 约束优化 [Maxima] R
- c# - “通过 POCO 类创建域模型”是什么意思?
- google-apps-script - 使用宏在 Google 工作表中复制和粘贴值不起作用