function tshirt_gif_text() {
woocommerce_wp_text_input(
array(
'id' => 'gif_tshirt',
'label' => __( 'GIF T-Shirt', 'woocommerce' ),
'placeholder' => 'http://',
'desc_tip' => 'true',
'description' => __( 'Them GIF links.', 'woocommerce' ),
'value' => get_post_meta( get_the_ID(), 'gif_tshirt', true )
)
);
}
add_action( 'woocommerce_product_options_advanced', 'tshirt_gif_text' );
function tshirt_gif_text_save( $post_id ) {
// update_post_meta( $post_id, 'gif_tshirt', $checkbox );
if (isset($_POST['gif_tshirt'])){
update_post_meta( $post_id, 'gif_tshirt', $_POST['gif_tshirt'], false );
}
if (!isset($_POST['gif_tshirt'])){
delete_post_meta( $post_id, 'gif_tshirt');
}
}
add_action( 'woocommerce_process_product_meta', 'tshirt_gif_text_save' );
I made a custom text field to add a link to a image. I'd like to use the Media uploader to upload or choose an image from the existent ones and update the "gif_tshirt" post meta with the link, but I don't know exactly how to start.
Add my media
I think as a button I can use this one.
And this is the JS
jQuery(function($) {
$(document).ready(function(){
$('#insert-my-media').click(open_media_window);
});
function open_media_window() {
if (this.window === undefined) {
this.window = wp.media({
title: 'Insert a media',
library: {type: 'image'},
multiple: false,
button: {text: 'Insert'}
});
var self = this; // Needed to retrieve our variable in the anonymous function below
this.window.on('select', function() {
var first = self.window.state().get('selection').first().toJSON();
wp.media.editor.insert('[myshortcode id="' + first.id + '"]');
});
}
this.window.open();
return false;
}
});
But it inserts this in the main description, how can i choose the destination?
I did it!
add_action('plugins_loaded', function(){
if($GLOBALS['pagenow']=='post.php'){
add_action('admin_print_scripts', 'my_admin_scripts');
add_action('admin_print_styles', 'my_admin_styles');
}
});
function my_admin_scripts(){
wp_enqueue_script('jquery');
wp_enqueue_script('media-upload');
wp_enqueue_script('thickbox');
}
function my_admin_styles(){
wp_enqueue_style('thickbox');
}
add_action(
'add_meta_boxes',
function(){
add_meta_box(
'my-metaboxx1', // ID
'Hover MP4 Catalog', // Title
'func99999', // Callback (Construct function)
get_post_types(), //screen (This adds metabox to all post types)
'side', // Context
'core'
);
},
999
);
function func99999($post){
$url =get_post_meta($post->ID,'gif_tshirt', true); ?>
<label for="video_URL">
<input id="video_URL" type="text" name="video_URL" value="<?php echo $url;?>" />
<input id="upload_video_button" class="button" type="button" value="Choose a Video" />
<br />Choose a video from the media library then, update your post/page to save it.<br /><br />
<?php
if ($url != "") {
?>
<video class="video" controls>
<source src="<?php echo $url;?>" type="video/mp4" id="vidsrc">
Your browser does not support HTML5 video.
</video>
<?php
}
?>
</label>
<script>
jQuery(document).ready(function($){
$('#video-metabox.postbox').css('margin-top','30px');
var custom_uploader;
$('#upload_video_button').click(function(e) {
e.preventDefault();
//If the uploader object has already been created, reopen the dialog
if (custom_uploader) {
custom_uploader.open();
return;
}
//Extend the wp.media object
custom_uploader = wp.media.frames.file_frame = wp.media({
title: 'Choose a Video',
button: {
text: 'Choose a Video'
},
multiple: false
});
//When a file is selected, grab the URL and set it as the text field's value
custom_uploader.on('select', function() {
attachment = custom_uploader.state().get('selection').first().toJSON();
$('#video_URL').val(attachment.url);
});
//Open the uploader dialog
custom_uploader.open();
});
});
</script>
<?php
}
add_action( 'save_post', function ($post_id) {
if (isset($_POST['video_URL'])){
update_post_meta($post_id, 'gif_tshirt',$_POST['video_URL']);
}
});
Related
I am using wordpress 4.7.2
I am trying to create a simple widget that will only help user to upload an image .
Below my code, when I am selecting an image , it gives me option to insert into post, but I want it not be associated to any post, just want its url and id so that I can use it to display.
I tried to follow use media upload in custom widget and create image uploader widget and wordpress custom widget image uplaaod but could not solved it.
<?php
namespace MyTheme\Widgets;
use \MyTheme\Widgets as Widgets;
class Image extends \WP_Widget {
public function __construct( $id_base = false, $name = false, $widget_options = array(), $control_options = array() ) {
$id_base = ( $id_base ) ? $id_base : 'mytheme-widget-image';
$name = ( $name ) ? $name : __( 'Image', 'mytheme-widget-image-i18n' );
$widget_options = wp_parse_args( $widget_options, array(
'classname' => 'widget_image',
'description' => __( 'An image from the media library', 'mytheme-widget-image-i18n' )
) );
$control_options = wp_parse_args( $control_options, array( 'width' => 300 ) );
parent::__construct( $id_base, $name, $widget_options, $control_options );
add_action('image_widget_print_footer_scripts', array(__CLASS__, 'print_footer_js') );
}
public function widget( $args, $instance ) {
$content = $this->render( $args, $wp_widget );
}
public function render( $args, $instance ){
//generate content
return $content;
}
public function form($instance){
$widget_img_id = isset($instance['widget_img_id']) ? $instance['widget_img_id'] : '';
$image_src = isset($instance['widget-img-id']) ? $instance['widget-img-id'] : '';
$upload_link = esc_url( get_upload_iframe_src( 'image', $widget_img_id ) );
$is_image = ! empty($image_src);
?>
<div class="widget-img-wrapper">
<div class="widget-img-container">
<?php if ( $is_image ): ?>
<img src="<?php echo $image_src; ?>" alt="" style="max-width:100%" />
<?php endif; ?>
<p class="hide-if-no-js">
<a name="upload_img_src" href="<?php echo $upload_link; ?>" class="upload-widget-img <?php if ( $is_image ){ echo 'hidden'; } ?>">
<?php _e('Set custom image') ?>
</a>
<a class="delete-widget-img <?php if ( ! $is_image ) { echo 'hidden'; } ?>"
href="#">
<?php _e('Remove this image') ?>
</a>
<input class="widget-img-id" name="widget_img_id" type="hidden" value="<?php echo esc_attr( $image_id ); ?>" />
</p>
</div>
</div>
<?php
}
public function update( $new_instance, $old_instance ){
$instance = array();
$instance['widget_img_id'] = ( ! empty( $new_instance['widget_img_id'] ) ) ? strip_tags( $new_instance['widget_img_id'] ) : '';
$instance['upload_img_src'] = ( ! empty( $new_instance['upload_img_src'] ) ) ? strip_tags( $new_instance['upload_img_src'] ) : '';
return $instance;
}
public static function print_footer_js()
{
wp_enqueue_media();
?>
<script>
jQuery(function($){
// Set all variables to be used in scope
var frame,
imageContainer = $('.widget-img-wrapper'), // Your meta box id here
addImgLink = imageContainer.find('.upload-widget-img'),
delImgLink = imageContainer.find( '.delete-widget-img'),
imgContainer = imageContainer.find( '.widget-img-container'),
imgIdInput = imageContainer.find( '.widget-img-id' );
// ADD IMAGE LINK
addImgLink.on( 'click', function( event ){
event.preventDefault();
// If the media frame already exists, reopen it.
if ( frame ) {
frame.open();
return;
}
// Create a new media frame
frame = wp.media({
title: 'Select or Upload Media Of Your Chosen Persuasion',
button: {
text: 'Use this media'
},
library: {
type: 'image'
}
multiple: false // Set to true to allow multiple files to be selected
});
// When an image is selected in the media frame...
frame.on( 'select', function() {
// Get media attachment details from the frame state
var attachment = frame.state().get('selection').first().toJSON();
// Send the attachment URL to our custom image input field.
imgContainer.append( '<img src="'+attachment.url+'" alt="" style="max-width:100%;"/>' );
// Send the attachment id to our hidden input
imgIdInput.val( attachment.id );
// Hide the add image link
addImgLink.addClass( 'hidden' );
// Unhide the remove image link
delImgLink.removeClass( 'hidden' );
});
// Finally, open the modal on click
frame.open();
});
// DELETE IMAGE LINK
delImgLink.on( 'click', function( event ){
event.preventDefault();
// Clear out the preview image
imgContainer.html( '' );
// Un-hide the add image link
addImgLink.removeClass( 'hidden' );
// Hide the delete image link
delImgLink.addClass( 'hidden' );
// Delete the image id from the hidden input
imgIdInput.val( '' );
});
});
</script>
<?php
}
}
I believe, taht "insert into post" is just the default text, and that it doesn't really have anything to do with the post - The file ends up in the media library and in the uploads folders anyway -
function replace_window_text($translated_text, $text) {
if ('Insert into Post' == $text) {
$referer = strpos(wp_get_referer(), 'media_page');
if ($referer != '') {
return __('Upload Billede', 'ink');
}
}
return $translated_text;
}
This is from one of my old projects, where I created a plugin for media uploading. probably doesn't fit your problem, but it can maybe put you on the right path
The issue with this is
add_action('image_widget_print_footer_scripts', array(__CLASS__, 'print_footer_js') ); is unable to enqueue script, neither wp_footer, admin_footer or admin_enqueue_scripts will be able to render script, need to enqueue outside the class. that solves my problem. Do not use this javascript, has problem with instance as used class in js.
<?php
namespace MyTheme\Widgets;
use \MyTheme\Widgets as Widgets;
class Image extends \WP_Widget {
public function __construct( $id_base = false, $name = false, $widget_options = array(), $control_options = array() ) {
$id_base = ( $id_base ) ? $id_base : 'mytheme-widget-image';
$name = ( $name ) ? $name : __( 'Image', 'mytheme-widget-image-i18n' );
$widget_options = wp_parse_args( $widget_options, array(
'classname' => 'widget_image',
'description' => __( 'An image from the media library', 'mytheme-widget-image-i18n' )
) );
$control_options = wp_parse_args( $control_options, array( 'width' => 300 ) );
parent::__construct( $id_base, $name, $widget_options, $control_options );
add_action('image_widget_print_footer_scripts', array(__CLASS__, 'print_footer_js') );
}
public function widget( $args, $instance ) {
$content = $this->render( $args, $wp_widget );
}
public function render( $args, $instance ){
//generate content
return $content;
}
public function form($instance){
$widget_img_id = isset($instance['widget_img_id']) ? $instance['widget_img_id'] : '';
$image_src = isset($instance['widget-img-id']) ? $instance['widget-img-id'] : '';
$upload_link = esc_url( get_upload_iframe_src( 'image', $widget_img_id ) );
$is_image = ! empty($image_src);
?>
<div class="widget-img-wrapper">
<div class="widget-img-container">
<?php if ( $is_image ): ?>
<img src="<?php echo $image_src; ?>" alt="" style="max-width:100%" />
<?php endif; ?>
<p class="hide-if-no-js">
<a name="upload_img_src" href="<?php echo $upload_link; ?>" class="upload-widget-img <?php if ( $is_image ){ echo 'hidden'; } ?>">
<?php _e('Set custom image') ?>
</a>
<a class="delete-widget-img <?php if ( ! $is_image ) { echo 'hidden'; } ?>"
href="#">
<?php _e('Remove this image') ?>
</a>
<input class="widget-img-id" name="widget_img_id" type="hidden" value="<?php echo esc_attr( $image_id ); ?>" />
</p>
</div>
</div>
<?php
}
public function update( $new_instance, $old_instance ){
$instance = array();
$instance['widget_img_id'] = ( ! empty( $new_instance['widget_img_id'] ) ) ? strip_tags( $new_instance['widget_img_id'] ) : '';
$instance['upload_img_src'] = ( ! empty( $new_instance['upload_img_src'] ) ) ? strip_tags( $new_instance['upload_img_src'] ) : '';
return $instance;
}
}
and JS
add_action( 'admin_enqueue_scripts', function(){
wp_enqueue_media('jquery');
} );
add_action('admin_footer', function(){
?>
<script>
jQuery(function($){
// Set all variables to be used in scope
var frame,
imageContainer = $('.widget-img-wrapper'), // Your meta box id here
addImgLink = imageContainer.find('.upload-widget-img'),
delImgLink = imageContainer.find( '.delete-widget-img'),
imgContainer = imageContainer.find( '.widget-img-container'),
imgIdInput = imageContainer.find( '.widget-img-id' );
// ADD IMAGE LINK
addImgLink.on( 'click', function( event ){
event.preventDefault();
// If the media frame already exists, reopen it.
if ( frame ) {
frame.open();
return;
}
// Create a new media frame
frame = wp.media({
title: 'Select or Upload Media Of Your Chosen Persuasion',
button: {
text: 'Use this media'
},
multiple: false // Set to true to allow multiple files to be selected
});
// When an image is selected in the media frame...
frame.on( 'select', function() {
// Get media attachment details from the frame state
var attachment = frame.state().get('selection').first().toJSON();
// Send the attachment URL to our custom image input field.
imgContainer.append( '<img src="'+attachment.url+'" alt="" style="max-width:100%;"/>' );
// Send the attachment id to our hidden input
imgIdInput.val( attachment.id );
// Hide the add image link
addImgLink.addClass( 'hidden' );
// Unhide the remove image link
delImgLink.removeClass( 'hidden' );
});
// Finally, open the modal on click
frame.open();
});
// DELETE IMAGE LINK
delImgLink.on( 'click', function( event ){
event.preventDefault();
// Clear out the preview image
imgContainer.html( '' );
// Un-hide the add image link
addImgLink.removeClass( 'hidden' );
// Hide the delete image link
delImgLink.addClass( 'hidden' );
// Delete the image id from the hidden input
imgIdInput.val( '' );
});
});
</script>
<?php
}
here is the code which I got from github page:
define('MY_POST_TYPE', 'my');
define('MY_POST_SLUG', 'gallery');
function my_register_post_type () {
$args = array (
'label' => 'Gallery',
'supports' => array( 'title', 'excerpt' ),
'register_meta_box_cb' => 'my_meta_box_cb',
'show_ui' => true,
'query_var' => true
);
register_post_type( MY_POST_TYPE , $args );
}
add_action( 'init', 'my_register_post_type' );
function my_meta_box_cb () {
add_meta_box( MY_POST_TYPE . '_details' , 'Media Library', 'my_meta_box_details', MY_POST_TYPE, 'normal', 'high' );
}
function my_meta_box_details () {
global $post;
$post_ID = $post->ID; // global used by get_upload_iframe_src
printf( "<iframe frameborder='0' src=' %s ' style='width: 100%%; height: 400px;'> </iframe>", get_upload_iframe_src('media') );
}
It shows my gallery page and media up-loader section on that page nicely, but there is no insert into post button inside that uploader and I am unable to insert image to that post. Additionally, If I upload image from my computer it has insert into post button, once I click upon that button page all my media up-loader screen disappears and nothing happens ? what's wrong with my code or approach please
You are missing editor in your supports:
define('MY_POST_TYPE', 'my');
define('MY_POST_SLUG', 'gallery');
function my_register_post_type () {
$args = array (
'label' => 'Gallery',
'supports' => array( 'title', 'excerpt', 'editor' ),
'register_meta_box_cb' => 'my_meta_box_cb',
'show_ui' => true,
'query_var' => true
);
register_post_type( MY_POST_TYPE , $args );
}
add_action( 'init', 'my_register_post_type' );
function my_meta_box_cb () {
add_meta_box( MY_POST_TYPE . '_details' , 'Media Library', 'my_meta_box_details', MY_POST_TYPE, 'normal', 'high' );
}
function my_meta_box_details () {
global $post;
$post_ID = $post->ID; // global used by get_upload_iframe_src
printf( "<iframe frameborder='0' src=' %s ' style='width: 100%%; height: 400px;'> </iframe>", get_upload_iframe_src('media') );
}
Once you add the editor, when you click 'Insert into post' you can see the inserted link in the editor. Which is presumably what you need.
There is a problem with disappearing metabox when you do upload the image.
In my opinion, you don't really need the extra uploader in a metabox. You have 'Add Media' Button above the editor - you can add images, videos or galleries in your CPT that way.
EDIT
You could ditch the media uploader and just call the default wp.media like this:
function my_meta_box_details () {
global $post;
// Here we get the current images ids of the gallery
$custom = get_post_custom($post->ID);
$my_gallery = (isset($custom["my_gallery"][0])) ? $custom["my_gallery"][0] : '';
// We display the gallery
?>
<style>
.gallery-item{
width:150px;
display: inline-block;
margin-right: 10px;
}
.gallery-item img{
width: 150px;
}
</style>
<div class="gallery_images">
<?php
$img_array = (isset($my_gallery) && $my_gallery != '') ? explode(',', $my_gallery) : '';
if ($img_array != '') {
foreach ($img_array as $img) {
echo '<div class="gallery-item">'.wp_get_attachment_image($img).'</div>';
}
}
?>
</div>
<p class="separator">
<input id="my_gallery_input" type="hidden" name="my_gallery" value="<?php echo $my_gallery; ?>" data-urls=""/>
<input id="manage_gallery" title="Manage gallery" type="button" value="Manage gallery" />
<input id="empty_gallery" title="Empty gallery" type="button" value="Empty gallery" />
</p>
<script>
jQuery(document).ready(function($) {
$(document).on('click', '#manage_gallery', upload_gallery_button);
function upload_gallery_button(e) {
e.preventDefault();
var $input_field = $('#my_gallery_input');
var ids = $input_field.val();
var gallerysc = '[gallery ids="' + ids + '"]';
wp.media.gallery.edit(gallerysc).on('update', function(g) {
var id_array = [];
var url_array = [];
$.each(g.models, function(id, img){
url_array.push(img.attributes.url);
id_array.push(img.id);
});
var ids = id_array.join(",");
ids = ids.replace(/,\s*$/, "");
var urls = url_array.join(",");
urls = urls.replace(/,\s*$/, "");
$input_field.val(ids);
var html = '';
for(var i = 0 ; i < url_array.length; i++){
html += '<div class="gallery-item"><img src="'+url_array[i]+'"></div>';
}
$('.gallery_images').html('').append(html);
});
}
$(document).on('click', '#empty_gallery', empty_gallery_button);
function empty_gallery_button(e){
e.preventDefault();
var $input_field = $('#my_gallery_input');
$input_field.val('');
$('.gallery_images').html('');
}
});
</script>
<?php
}
function my_metabox_save(){
global $post;
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) {
return;
} elseif(is_object($post)){
$my_gallery = (isset($_POST['my_gallery'])) ? $_POST['my_gallery'] : '';
update_post_meta($post->ID, 'my_gallery', $my_gallery);
}
}
add_action('save_post', 'my_metabox_save');
And remove the editor from your supports argument. Should be working fine.
hi I'm trying without reload Woo-commerce Shop page product per page but its reload of selected number...
Now it's working but page reload then work I need to without reload of shop page
anybody help me
add_action('wp_head','theme_ajaxurl');
function theme_ajaxurl() {
?>
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<?php
}
add_action( 'wp_ajax_nopriv_dl_sort_by_page', 'woocommerce_catalog_per_page_ordering' );
add_action( 'wp_ajax_dl_sort_by_page', 'woocommerce_catalog_per_page_ordering' );
function woocommerce_catalog_per_page_ordering() {
?>
<form action="" method="POST" name="results">
<select name="woocommerce-sort-by-columns" id="woocommerce-sort-by-columns" class="sortby">
<?php
// This is where you can change the amounts per page that the user will use feel free to change the numbers and text as you want, in my case we had 4 products per row so I chose to have multiples of four for the user to select.
$shopCatalog_orderby = apply_filters('woocommerce_sortby_page', array(
'' => __('Products per page', 'woocommerce'),
'8' => __('8 per page', 'woocommerce'),
'16' => __('16 per page', 'woocommerce'),
'32' => __('32 per page', 'woocommerce'),
'-1' => __('View All', 'woocommerce'),
));
foreach ( $shopCatalog_orderby as $sort_id => $sort_name )
echo '<option value="' . $sort_id . '" ' . selected( $_SESSION['sortby'], $sort_id, false ) . ' >' . $sort_name . '</option>';
?>
</select>
</form>
<?php // Adrian's code
if (isset($_POST['woocommerce-sort-by-columns']) && (($_COOKIE['shop_pageResults'] <> $_POST['woocommerce-sort-by-columns']))) {
$currentProductsPerPage = $_POST['woocommerce-sort-by-columns'];
} else {
$currentProductsPerPage = $_COOKIE['shop_pageResults'];
}
?>
<script type="text/javascript">
jQuery('select.sortby>option[value="<?php echo $currentProductsPerPage; ?>"]').attr('selected', true);
</script>
<?php
}
// now we set our cookie if we need to
function dl_sort_by_page($count) {
if (isset($_COOKIE['shop_pageResults'])) { // if normal page load with cookie
$count = $_COOKIE['shop_pageResults'];
}
if (isset($_POST['woocommerce-sort-by-columns'])) { //if form submitted
setcookie('shop_pageResults', $_POST['woocommerce-sort-by-columns'], time()+1209600, '/', 'yourdomain.com', false); //this will fail if any part of page has been output- hope this works!
$count = $_POST['woocommerce-sort-by-columns'];
}
// else normal page load and no cookie
return $count;
}
add_filter('loop_shop_per_page','dl_sort_by_page');
Script Code
<script>
jQuery( document ).on( 'change', '#woocommerce-sort-by-columns', function(event) {
event.preventDefault();
var post_id = jQuery('select.sortby').val();
jQuery.ajax({
url : ajaxurl,
type : 'POST',
data : {
action : 'dl_sort_by_page'
},
success : function( response ) {
alert('ok');
}
});
})
</script>
Using the following code, I'm trying to allow only certain image types to be upload/selected with the WordPress media API. So I'm using add_filter on upload_mimes to restrict the mime types allowed. Using get_allowed_mime_types() I get an array containing only the mime types I want. However, when I click the change image button, I'm still able to upload files of mime types not listed before (such as PDF). What am I doing wrong?
public static function file_uploader( $element_id = null, $multiple = true )
{
add_filter( 'upload_mimes', array( 'JBLAB_Utils', 'images_upload_mimes' ) );
var_dump( get_allowed_mime_types() );
/**
* outputs:
* array(3) {
* ["jpg|jpeg|jpe"]=>
* string(10) "image/jpeg"
* ["gif"]=>
* string(9) "image/gif"
* ["png"]=>
* string(9) "image/png"
* }
*/
$multiple = ( $multiple === true ) ? 'true' : 'false';
wp_enqueue_script('jquery');
wp_enqueue_media();
?>
<div>
<?php
if ( empty( $element_id ) )
{
$element_id = "jblab_uploaded_file_url";
?>
<label for="jblab_uploaded_file_url"><?php _e( 'Image', 'jblab-radionomy' ); ?></label>
<input type="text" name="jblab_uploaded_file_url" id="jblab_uploaded_file_url" class="regular-text">
<?php
}
?>
<input type="button" name="jblab_upload_file_upload_btn" id="jblab_upload_upload_btn" class="button-secondary" value="<?php _e( 'Change Image', 'jblab-radionomy' ); ?>">
</div>
<script type="text/javascript">
jQuery(document).ready(function($){
$('#jblab_upload_upload_btn').click(function(e) {
e.preventDefault();
var image = wp.media({
title: '<?php echo str_replace( "'", "\'", __( 'Change Image', 'jblab-radionomy' ) ); ?>',
multiple: <?php echo $multiple; ?>
}).open()
.on('select', function(e){
var uploaded_image = image.state().get('selection').first();
var image_url = uploaded_image.toJSON().url;
<?php
echo "
if ($('#$element_id').is('img')) {
$('#$element_id').attr('src',image_url);
} else {
$('#$element_id').val(image_url);
}
";
?>
});
});
});
</script>
<?php
}
public static function images_upload_mimes ( $mimes = array() )
{
//unset( $mimes );
$mimes = array(
'jpg|jpeg|jpe' => 'image/jpeg',
'gif' => 'image/gif',
'png' => 'image/png',
);
return $mimes;
}
Ok, so I found a solution to my issue.
I had to move the add_filter outside of the function that is calling the upload API. If anybody has the same problem, try to add_filters as soon as possible in the process, that should do the trick.
I am developing a wordpress plugin and I need to have a field where I can upload an image. Since wordpress has a very handly uploader it would be great if I could use that.
anyone know if that's possible?
Thanks
If you only want to upload a file, you don't need the media uploader. A simple form is all you need.
To call the media uploader you need a link like this:
<a onclick="return false;" title="Upload image" class="thickbox" id="add_image" href="media-upload.php?type=image&TB_iframe=true&width=640&height=105">Upload Image</a>
You'll maybe have to append your URL to media-upload.php to make it working.
YOu can use wordpress default media file uploader by using this code and simply retrieve link of image in jquery
<label for="upload_image">
<input id="upload_image" type="text" size="36" name="ad_image" value="http://" />
<input id="upload_image_button" class="button" type="button" value="Upload Image" />
<br />Enter a URL or upload an image
</label>
<?php
add_action('admin_enqueue_scripts', 'my_admin_scripts');
function my_admin_scripts() {
if (isset($_GET['page']) && $_GET['page'] == 'my_plugin_page') {
wp_enqueue_media();
wp_register_script('my-admin-js', WP_PLUGIN_URL.'/my-plugin/my-admin.js', array('jquery'));
wp_enqueue_script('my-admin-js');
}
}
?>
<script>
jQuery(document).ready(function($){
var custom_uploader;
$('#upload_image_button').click(function(e) {
e.preventDefault();
//If the uploader object has already been created, reopen the dialog
if (custom_uploader) {
custom_uploader.open();
return;
}
//Extend the wp.media object
custom_uploader = wp.media.frames.file_frame = wp.media({
title: 'Choose Image',
button: {
text: 'Choose Image'
},
multiple: true
});
//When a file is selected, grab the URL and set it as the text field's value
custom_uploader.on('select', function() {
console.log(custom_uploader.state().get('selection').toJSON());
attachment = custom_uploader.state().get('selection').first().toJSON();
$('#upload_image').val(attachment.url);
});
//Open the uploader dialog
custom_uploader.open();
});
});
</script>
Hi you can use the following code,
<?php
if ( isset( $_POST['submit_image_selector'] ) && isset( $_POST['image_attachment_id'] ) ) :
update_option( 'media_selector_attachment_id', absint( $_POST['image_attachment_id'] ) );
endif;
wp_enqueue_media();
?><form method='post'>
<div class='image-preview-wrapper'>
<img id='image-preview' src='<?php echo wp_get_attachment_url( get_option( 'media_selector_attachment_id' ) ); ?>' width='200'>
</div>
<input id="upload_image_button" type="button" class="button" value="<?php _e( 'Upload image' ); ?>" />
<input type='hidden' name='image_attachment_id' id='image_attachment_id' value='<?php echo get_option( 'media_selector_attachment_id' ); ?>'>
<input type="submit" name="submit_image_selector" value="Save" class="button-primary">
</form>
<?php
$my_saved_attachment_post_id = get_option( 'media_selector_attachment_id', 0 );
?><script type='text/javascript'>
jQuery( document ).ready( function( $ ) {
// Uploading files
var file_frame;
var wp_media_post_id = wp.media.model.settings.post.id; // Store the old id
var set_to_post_id = <?php echo $my_saved_attachment_post_id; ?>; // Set this
jQuery('#upload_image_button').on('click', function( event ){
event.preventDefault();
// If the media frame already exists, reopen it.
if ( file_frame ) {
// Set the post ID to what we want
file_frame.uploader.uploader.param( 'post_id', set_to_post_id );
// Open frame
file_frame.open();
return;
} else {
// Set the wp.media post id so the uploader grabs the ID we want when initialised
wp.media.model.settings.post.id = set_to_post_id;
}
// Create the media frame.
file_frame = wp.media.frames.file_frame = wp.media({
title: 'Select a image to upload',
button: {
text: 'Use this image',
},
multiple: false // Set to true to allow multiple files to be selected
});
// When an image is selected, run a callback.
file_frame.on( 'select', function() {
// We set multiple to false so only get one image from the uploader
attachment = file_frame.state().get('selection').first().toJSON();
// Do something with attachment.id and/or attachment.url here
$( '#image-preview' ).attr( 'src', attachment.url ).css( 'width', 'auto' );
$( '#image_attachment_id' ).val( attachment.id );
// Restore the main post ID
wp.media.model.settings.post.id = wp_media_post_id;
});
// Finally, open the modal
file_frame.open();
});
// Restore the main ID when the add media button is pressed
jQuery( 'a.add_media' ).on( 'click', function() {
wp.media.model.settings.post.id = wp_media_post_id;
});
});
</script>