对于使用 WordPress 的媒体上传器上传的图像,有一个“插入到帖子”按钮,用于向编辑器发送该图像的短代码。
我有一个文本输入,当聚焦时,我希望媒体上传器出现,以便用户可以选择图像并将文件 URL 发送到文本输入。
我遇到的主要问题是创建附加的“插入帖子”按钮,将文件 URL 发送到相应的文本字段。
我应该使用哪个钩子,如何将文件 URL 数据返回到输入字段?
感谢您的指导!
你所描述的是旧的 Wordpress 做它的方式......如果你想在 Wordpress 3.5+ 中使用新的上传器,你可以创建一个wp.media
对象来上传它,类似于 wp-admin/js/custom 中的代码-background.js:
// Create the media frame.
frame = wp.media.frames.customBackground = wp.media({
// Set the title of the modal.
title: $el.data('choose'),
// Tell the modal to show only images.
library: {
type: 'image'
},
// Customize the submit button.
button: {
// Set the text of the button.
text: $el.data('update'),
// Tell the button not to close the modal, since we're
// going to refresh the page when the image is selected.
close: false
}
});
// When an image is selected, run a callback.
frame.on( 'select', function() {
// Grab the selected attachment.
var attachment = frame.state().get('selection').first();
// Run an AJAX request to set the background image.
$.post( ajaxurl, {
action: 'set-background-image',
attachment_id: attachment.id,
size: 'full'
}).done( function() {
// When the request completes, reload the window.
window.location.reload();
});
});
// Finally, open the modal.
frame.open();
选择frame.on('select' function(){
文件时运行代码。
进一步搜索,我找到了一些很好的资源来解释如何做到这一点。我选择了 JavaScript、PHP 组合:
$j('input').live('focusin',function(){
var target = '#'+$j(this).attr('id');
tb_show('','media-upload.php?post_id=[post_id]&tab=gallery&context=choose&TB_iframe=1');
window.send_to_editor = function(html) {
fileurl = $j(html).attr('href');
$j(target).val(fileurl);
tb_remove();
};
});
来源:http: //jaspreetchahal.org/wordpress-using-media-uploader-in-your-plugin/
/* Customize button */
function media_uploader_btn($form_fields, $post) {
$send = "<input type='submit' class='button' name='send[$post->ID]' value='" . esc_attr__( 'Choose This File' ) . "' />";
$form_fields['buttons'] = array('tr' => "\t\t<tr class='submit'><td></td><td class='savesend'>$send</td></tr>\n");
$form_fields['context'] = array( 'input' => 'hidden', 'value' => 'choose' );
return $form_fields;
}
/* Check for button context */
function check_upload_image_context($context){
if(isset($_REQUEST['context']) && $_REQUEST['context'] == $context){
return true;
} elseif(isset($_POST['attachments']) && is_array($_POST['attachments'])){
/* check for context in attachment objects */
$image_data = current($_POST['attachments']);
if (isset($image_data['context']) && $image_data['context'] == $context ){
return true;
}
}
return false;
}
if(check_upload_image_context('choose')){
add_filter('attachment_fields_to_edit', 'media_uploader_btn', 20, 2);
}
来源:http ://shibashake.com/wordpress-theme/how-to-hook-into-the-media-upload-popup-interface