如何通过cmb2获取上传的图片位置url


How to get uploaded image location url by cmb2

我在类似的cmb2元盒中创建了一个图像添加文件字段

$FF_side_settings->add_field( array(
        'name'    => 'Upload background image',
        'desc'    => 'Upload an image or enter an URL.',
        'id'      => 'ff_image_upload',
        'type'    => 'file',
        // Optional:
        'options' => array(
            'url' => true, 
            'add_upload_file_text' => 'Add image' 
        ),
    ) );

我想获得图像位置,并在我的div图像背景url 中显示值

<div class="fun-bg " style='background-image: url("'.$image.'");'>

我用了wp_get_attachment_image( get_post_meta( get_the_ID(), 'ff_image_upload', 1 ), 'medium' );,但我没能做到。有人能帮我找出我的问题在哪里吗?请解决。。。。。。。。。。。。

OK wp_get_attachment_image()返回图像标签:

<img src="image_src" ... />

在您的情况下,您需要回波功能返回

<div class="fun-bg">
<?php echo wp_get_attachment_image( get_post_meta( get_the_ID(), 'ff_image_upload', 1 ), 'medium' ); ?>
</div>

或者只获取src属性,而不获取image标签本身。

编辑:我安装了这个插件,并用图像元盒做了一些测试。

所以当您通过这个插件添加图像时,它会在postmeta表中创建两条记录。第一个是具有post的值id的元密钥ff_image_upload_id(在我的情况下为52),第二个是具有密钥ff_image_upload和值=image_path。

get_post_meta( get_the_ID(), 'ff_image_upload', 1 )将返回图像路径-http://host/site-name/wp-content/uploads/year/month/name.jpg

这是原始图像的路径,而不是"中等"、"缩略图"或类似的路径

get_post_meta( get_the_ID(), 'ff_image_upload_id', 1 )将返回post_id(52)。

如果您想使用wp_get_attachment_image()直接显示图像,则必须在帖子id中添加id,因此您必须这样使用它:

<?php echo wp_get_attachment_image( get_post_meta( get_the_ID(), 'ff_image_upload_id', 1 ), 'medium' ); ?>

如果您想要图像的url,这将返回medium图像的url

<?php wp_get_attachment_image_src( get_post_meta( get_the_ID(), 'ff_image_upload_id', 1 ), 'medium' )[0]; ?>