首页 > 解决方案 > 在 Gutenberg 块的后端视图中使用附件 ID 属性获取附件 url

问题描述

如果 Gutenberg 块存储了附件 ID 属性,是否有办法使用该 ID 动态获取特定缩略图大小的 url?

该属性将像这样存储在块中:

 imageID: {
     type: 'integer',
 },

这个想法是在 Gutenberg 编辑器视图中动态显示该图像。

标签: wordpresswordpress-gutenberggutenberg-blocks

解决方案


几周前我遇到了这个问题。它让我困惑了一段时间,但你可以使用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 加载页面时加载。希望这会有所帮助。


推荐阅读