Wordpress - 使用媒体库获取图像

     2023-02-24     260

关键词:

【中文标题】Wordpress - 使用媒体库获取图像【英文标题】:Wordpress - Get an image using the media library 【发布时间】:2015-12-29 19:01:49 【问题描述】:

我正在创建一个插件,我有一个管理页面

在该页面的选项中,我想添加一个按钮,允许我打开 Wordpress 媒体库并从中选择一个图像,然后获取所选图像的 URL 和 alt 属性。

如果可能的话,我如何使用 AJAX 做到这一点?

【问题讨论】:

【参考方案1】:

首先,您需要将 wordpress 核心媒体脚本和自定义 js 脚本加入队列

function my_enqueue_media_lib_uploader() 

    //Core media script
    wp_enqueue_media();

    // Your custom js file
    wp_register_script( 'media-lib-uploader-js', plugins_url( 'media-lib-uploader.js' , __FILE__ ), array('jquery') );
    wp_enqueue_script( 'media-lib-uploader-js' );

add_action('admin_enqueue_scripts', 'my_enqueue_media_lib_uploader');

然后假设您在选项页面中有这个标记:一个上传按钮和一个用于存储所选图像 url 的文本输入

<form method="post">
    <input id="image-url" type="text" name="image" />
    <input id="upload-button" type="button" class="button" value="Upload Image" />
    <input type="submit" value="Submit" />
</form>

您需要添加此 javascript 代码来调用上传器弹出窗口

jQuery(document).ready(function($)

  var mediaUploader;

  $('#upload-button').click(function(e) 
    e.preventDefault();
    // If the uploader object has already been created, reopen the dialog
      if (mediaUploader) 
      mediaUploader.open();
      return;
    
    // Extend the wp.media object
    mediaUploader = wp.media.frames.file_frame = wp.media(
      title: 'Choose Image',
      button: 
      text: 'Choose Image'
    , multiple: false );

    // When a file is selected, grab the URL and set it as the text field's value
    mediaUploader.on('select', function() 
      attachment = mediaUploader.state().get('selection').first().toJSON();
      $('#image-url').val(attachment.url);
    );
    // Open the uploader dialog
    mediaUploader.open();
  );

);

选择图像后,您的 image-url 输入现在将包含该 url,并将保存在表单提交中。

【讨论】:

【参考方案2】:

用例是:我有一个包含 index.php 作为主文件的插件,我希望能够单击一个按钮并打开媒体库并从中选择一个图像,这个图像应该加载到一个图像中标记。

1- 将脚本添加到您的主 PHP 插件

// index.php

// ...

// add script js for page
add_action('admin_enqueue_scripts', function () 
    // Enqueue WordPress media scripts
    if ($_GET["page"]== 'debug_area') 
        wp_enqueue_media();
        // Enqueue custom script that will interact with wp.media
        wp_enqueue_script(
            'myprefix_script',
            plugins_url('/load_img.js', __FILE__),
            array('jquery'),
            '0.1');
    
);

// add ajax action to get the image async
add_action('wp_ajax_get_image_from_media_lib', function () 
    if (isset($_GET['id'])) 
        $image = wp_get_attachment_image(
            filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT),
            'medium',
            false,
            array('id' => 'image_preview')
        );
        $data = array(
            'image' => $image,
        );
        wp_send_json_success($data);
     else 
        wp_send_json_error();
    
);

2-添加已经包含在enqueue中的文件JS

// load_img.js
jQuery(document).ready(_ => 
    console.clear();

    /**
     * Define media_lib_frame as wp.media object
     */
    const media_lib_frame = wp.media(
        title: 'Select Media',
        multiple: false,
        library: 
            type: 'image',
        
    );

    /**
     * On close, get selections and save to the hidden input
     * plus other AJAX stuff to refresh the image preview
     */
    media_lib_frame.on('close', _ => 
        const selection = media_lib_frame.state().get('selection');
        const gallery_ids = selection.map(attachment => attachment['id']);
        const ids = gallery_ids.join(",");
        jQuery('input#idImage').val(ids);
        loadImage(ids);
    );

    /**
     * On open, get the id from the hidden input
     * and select the appropriate images in the media manager
     */
    media_lib_frame.on('open', _ => 
        const selection = media_lib_frame.state().get('selection');
        const ids = jQuery('input#idImage').val().split(',');
        ids.forEach(id => 
            const attachment = wp.media.attachment(id);
            attachment.fetch();
            selection.add(attachment ? [attachment] : []);
        );
    );

    jQuery('button#btnOpenMediaLibFrame').click(e => 
        e.preventDefault();
        media_lib_frame.open();
    );
);

// Ajax request to refresh the image preview
const loadImage = the_id => 
    const data = action: 'get_image_from_media_lib', id: the_id;

    jQuery.get(ajaxurl, data, response => 
        if (response.success === true) 
            jQuery('#image_preview').replaceWith(response.data.image);
        
    );

3-将此HTML添加到负责渲染视图的函数中

<img id="image_preview"/>
<input
    type="hidden"
    id="idImage"
    class="regular-text"/>
<button
    type='button'
    class="button-primary"
    id="btnOpenMediaLibFrame">
    Select a image
</button>

【讨论】:

在 foreach 循环中使用媒体 ID 获取 WordPress 图像

】在foreach循环中使用媒体ID获取WordPress图像【英文标题】:GetWordPressimagesusingmediaIDinaforeachloop【发布时间】:2015-06-1107:41:00【问题描述】:我已经看到如何获取媒体库中的所有图像,反之亦然,从帖子库中获取图像,精选缩略图... 查看详情

我需要从我的 wordpress 媒体库中删除重复的图像

】我需要从我的wordpress媒体库中删除重复的图像【英文标题】:Ineedtoremoveduplicateimagesfrommywordpressmedialibrary【发布时间】:2014-04-1200:22:04【问题描述】:我正在尝试从我的wordpress媒体库中删除重复的图像。帖子本身不重复,但每... 查看详情

php[将图像上传到媒体库]将图像上传到媒体库并将其设置为$post_id(如果已指定)的特色图像。#wordpress(代码片段)

查看详情

如何在 Wordpress 的媒体库中删除图像的永久链接(登录页面)?

】如何在Wordpress的媒体库中删除图像的永久链接(登录页面)?【英文标题】:Howtodeletethepermalink(landingpages)ofimageinthemedialibraryinWordpress?【发布时间】:2019-01-0120:42:07【问题描述】:我注意到上传到wordpress网站的每张图片都会有... 查看详情

获取所有媒体文件 wordpress 的功能是啥?

】获取所有媒体文件wordpress的功能是啥?【英文标题】:Whatisthefunctiongotgetallthemediafileswordpress?获取所有媒体文件wordpress的功能是什么?【发布时间】:2011-03-1911:10:45【问题描述】:谁能建议我获取所有为wordpress存储的图像的功... 查看详情

限制用户在使用 wordpress 媒体编辑器选择特色图像时裁剪图像

】限制用户在使用wordpress媒体编辑器选择特色图像时裁剪图像【英文标题】:Restrictusertocropimageonselectingfeaturedimageusingwordpressmediaeditor【发布时间】:2020-01-2317:16:54【问题描述】:我试图限制用户仅以2:1或6:9等宽高比选择特色图像... 查看详情

php使用bxslider的wordpress媒体库。(代码片段)

查看详情

更改 Wordpress 媒体图像 URL

】更改Wordpress媒体图像URL【英文标题】:ChangeWordpressmediaimageURL【发布时间】:2020-06-1413:40:17【问题描述】:我对wordpress开发比较陌生。我在我的网站上安装了SSL证书。SSL挂锁在某些页面上不可见,并认为这是一个混合内容问题... 查看详情

从 Magento 中的产品集合中获取产品媒体库图像

】从Magento中的产品集合中获取产品媒体库图像【英文标题】:GetProductMediaGalleryImagesfromaProductCollectioninMagento【发布时间】:2011-12-1423:49:09【问题描述】:我在Magento中有一系列产品,我希望能够从中获取媒体库图像。但是我发现... 查看详情

WordPress 灯箱库:将文字链接打开到图片库

】WordPress灯箱库:将文字链接打开到图片库【英文标题】:WordPressLightboxGallery:Makingawordlinkopentoanimagegallery【发布时间】:2019-07-2212:48:37【问题描述】:我正在尝试获取打开灯箱画廊的文字链接。我的意思是让一个像“随机房间名... 查看详情

Wordpress Gutenberg 媒体上传视频库

】WordpressGutenberg媒体上传视频库【英文标题】:WordpressGutenbergMediaUploadVideoGallery【发布时间】:2019-10-2610:08:19【问题描述】:我想要在向&lt;MediaUpload&gt;组件提供gallery属性时使用的媒体上传弹出窗口。与普通Mediaupload的不同... 查看详情

WP媒体库网格视图不显示

...布时间】:2016-10-1404:56:08【问题描述】:发现这个问题:Wordpress:medialibrarygridmodeinfiniteloading而且,最近:“目前我正在使用Enfold子主题,但媒体网格视图不起作用。即使我尝试从其他任何地方进入网格,例如选择特色图像,它也... 查看详情

wordpress媒体库图片无法显示?

使用了woocommerce准备搭建一个电商网站。把图片上传到媒体库的时候却不能正确显示图片。Console显示太多次重定向,安装了一些https的插件也都不管用。具体操作如下:a)检查你是否设置了文章的特色图进入“编辑文章”页面,... 查看详情

如何在无头 wordpress 环境中确保图像请求的 CORS?

】如何在无头wordpress环境中确保图像请求的CORS?【英文标题】:HowdoIensureCORSforimagerequestsinaheadlesswordpressenv?【发布时间】:2019-04-0323:35:45【问题描述】:从HeadlessWordpressStarterKit开始,我从Wordpress媒体库中获取两张图片,并将它们... 查看详情

wordpress获取文章特色图像路径函数wp_get_attachment_image_src()(代码片段)

特色图像是wordpress主要的文章缩略图功能,几乎全部wordpress模板都使用或支持特色图像。今天介绍的wp_get_attachment_image_src()函数就是获取文章特色图像路径的wordpress函数,通过该函数可以返回一个包含图片路径、宽度和高度的有... 查看详情

php使用帖子附件的wordpress图像库短代码(代码片段)

查看详情

Wordpress 媒体缩略图/固定链接

】Wordpress媒体缩略图/固定链接【英文标题】:WordpressMediaThumbnail/Permalink【发布时间】:2016-03-1523:57:03【问题描述】:我的Wordpress安装有问题。我不知道什么时候发生的,所以也许有人可以帮助我找到问题。突然间,我所有的媒... 查看详情

wordpress媒体库上传不了视频。怎么回事?

WordPress媒体库上传不了视频。怎么回事,视频大小也没有超过。说是什么文件不合法,,参考技术A修改wp-config.php文件,这个文件在WordPress的根目录下,在其中增加一行语句:define(‘ALLOW_UNFILTERED_UPLOADS’,true);可以不限制上传类... 查看详情