更新媒体库附件

时间:2019-01-17 作者:gardelin

我通过以下方式将图像导入wordpresswp_insert_attachment.

在前端,wordpress媒体库仍然不知道图像是否已导入。我需要一种方法来更新媒体库中的附件而不刷新页面。

我找到了部分解决方案:

wp.media.frame.on(\'open\', function() {
    if (wp.media.frame.content.get() !== null) {          
        wp.media.frame.content.get().collection.props.set({ignore: (+ new Date())});
        wp.media.frame.content.get().options.selection.reset();
        } else {
            wp.media.frame.library.props.set({ignore: (+ new Date())});
        }
}, this);
这部分代码的问题是,现在当我尝试使用媒体库上载器上载照片时,图像已正确上载,但未显示。

2 个回复
最合适的回答,由SO网友:z1ad 整理而成

编辑:好的在这方面工作了一个小时后,我终于找到了一个解决方案,它可以在不影响上传的情况下工作,也不会干扰忽略或重置

wp.media.frame.on(\'open\', function() {
    if (wp.media.frame.content.get() !== null) {          
        // this forces a refresh of the content
        wp.media.frame.content.get().collection._requery(true);

        // optional: reset selection
        wp.media.frame.content.get().options.selection.reset();
    }
}, this);

SO网友:Nour Edin Al-Habal

这取决于您如何使用wp_insert_attachment(). 下面是从中复制的完整示例the codex:

// $filename should be the path to a file in the upload directory.
$filename = \'/path/to/uploads/2013/03/filename.jpg\';

// The ID of the post this attachment is for.
$parent_post_id = 37;

// Check the type of file. We\'ll use this as the \'post_mime_type\'.
$filetype = wp_check_filetype( basename( $filename ), null );

// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();

// Prepare an array of post data for the attachment.
$attachment = array(
    \'guid\'           => $wp_upload_dir[\'url\'] . \'/\' . basename( $filename ), 
    \'post_mime_type\' => $filetype[\'type\'],
    \'post_title\'     => preg_replace( \'/\\.[^.]+$/\', \'\', basename( $filename ) ),
    \'post_content\'   => \'\',
    \'post_status\'    => \'inherit\'
);

// Insert the attachment.
$attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );

// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
require_once( ABSPATH . \'wp-admin/includes/image.php\' );

// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );

//If you want to set it as a thumbnail
set_post_thumbnail( $parent_post_id, $attach_id );