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>
Related
I have an ACF Field called avatar on User Form (is this wrong?) which would work correctly, I can set the avatar image for each users. This field however is being nulled (disappears) from time to time, I have read countless topics trying to find somebody with similar problem but I had no luck.
This is a WP Multisite. The images I uploaded for the users are already thumbnail sizes (150x150), since WP would make this Thumbnail sizes itself (image preview size is set to thumbnail too), could it lead to some errors and that to disappearing images? Doesn't make much sense because then they'd be supposed to disappear as soon as I add them. It doesn't happen to all of the users in the same time.
If you need any more information feel free to ask.
The issue was related to WP Multisite. Whenever we changed a user's avatar on one of the sites in the other sites it was removed. We thought that these datas are handled separately, but unfortunately not. So we decided to create user meta fields instead and it seems to work just as we need it to work.
I add the code that worked for me (took a bit long to make it work and I copied most of them from different sources), maybe it helps somebody. (the hard part was the image)
add_action('show_user_profile', 'media_selector_settings_page_callback');
add_action('edit_user_profile', 'media_selector_settings_page_callback');
function media_selector_settings_page_callback($user)
{
// Save attachment ID
if (isset($_POST['submit_image_selector']) && isset($_POST['avatar-en'])) :
update_user_meta($user->ID, 'avatar-en', absint($_POST['avatar-en']));
endif;
wp_enqueue_media();
?>
<h3><?php _e("Extra profile information", "blank"); ?></h3>
<table class="form-table">
<tr>
<th><label for="bio-en"><?php _e("Bio-en"); ?></label></th>
<td>
<textarea name="bio-en" id="bio-en" class="regular-text" rows="8"><?php echo esc_attr(get_the_author_meta('bio-en', $user->ID)); ?></textarea>
<span class="description"><?php _e("Please enter your bio-en."); ?></span>
</td>
</tr>
<tr>
<th><label for="avatar"><?php _e("Avatar-en"); ?></label></th>
<td>
<div class='image-preview-wrapper'>
<img id='image-preview-en' src='<?php echo wp_get_attachment_url(esc_attr(get_the_author_meta('avatar-en', $user->ID))); ?>' height='100'>
</div>
<input id="upload_image_button" type="button" class="button" value="<?php _e('Upload image'); ?>" />
<input type='hidden' name='avatar-en' id='avatar-en' value='<?php echo esc_attr(get_the_author_meta('avatar-en', $user->ID)); ?>'>
</td>
</tr>
<tr>
<th><label for="bio-de"><?php _e("Bio-de"); ?></label></th>
<td>
<textarea name="bio-de" id="bio-de" class="regular-text" rows="8"><?php echo esc_attr(get_the_author_meta('bio-de', $user->ID)); ?></textarea>
<span class="description"><?php _e("Please enter your bio-de."); ?></span>
</td>
</tr>
<tr>
<th><label for="avatar"><?php _e("Avatar-de"); ?></label></th>
<td>
<div class='image-preview-wrapper'>
<img id='image-preview-de' src='<?php echo wp_get_attachment_url(esc_attr(get_the_author_meta('avatar-de', $user->ID))); ?>' height='100'>
</div>
<input id="upload_image_button-de" type="button" class="button" value="<?php _e('Upload image'); ?>" />
<input type='hidden' name='avatar-de' id='avatar-de' value='<?php echo esc_attr(get_the_author_meta('avatar-de', $user->ID)); ?>'>
</td>
</tr>
</table>
<?php
}
add_action('admin_footer', 'media_selector_print_scripts');
function media_selector_print_scripts()
{
$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-en').attr('src', attachment.url).css('width', 'auto');
$('#avatar-en').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>
<?php
}
add_action('admin_footer', 'media_selector_print_scripts_de');
function media_selector_print_scripts_de()
{
$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-de').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-de').attr('src', attachment.url).css('width', 'auto');
$('#avatar-de').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>
<?php
}
add_action('personal_options_update', 'save_extra_user_profile_fields');
add_action('edit_user_profile_update', 'save_extra_user_profile_fields');
function save_extra_user_profile_fields($user_id)
{
update_user_meta($user_id, 'avatar-en', absint($_POST['avatar-en']));
update_user_meta($user_id, 'avatar-de', absint($_POST['avatar-de']));
update_user_meta($user_id, 'bio-en', $_POST['bio-en']);
update_user_meta($user_id, 'bio-de', $_POST['bio-de']);
}
$args = array(
'single' => true,
'show_in_rest' => true,
);
register_meta('user', 'avatar-en', $args);
register_meta('user', 'avatar-de', $args);
register_meta('user', 'bio-en', $args);
register_meta('user', 'bio-de', $args);
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']);
}
});
I am the administrator on my website, but I can't change the profile photo for any of my user's. It seems to be hooked up only to Gravatar.
How do I make it so I can change this photo myself ? Is there a function to do this ? I'd rather not have an entire plugin to do so.
By default, WordPress uses Gravatar for displaying user’s profile picture based on your email ID registered with Gravatar. WordPress has user profile page in dashboard which contains number of fields for entering user data, but it lacks image field for adding custom user avatar.
We can customize user avatar in following steps:
Step 1: Add script to page.
In this step we will add necessary Javascript to admin pages. First we will call wp_enqueue_media which enqueues all scripts, styles, settings, and templates necessary to use all media JavaScript APIs.
Another script will be for opening media uploader on button click and to insert attachment id in DOM.
please copy following script into a file and name that file as uploader.js
jQuery( document ).ready( function() {
/* WP Media Uploader */
var _shr_media = true;
var _orig_send_attachment = wp.media.editor.send.attachment;
jQuery( '.shr-image' ).click( function() {
var button = jQuery( this ),
textbox_id = jQuery( this ).attr( 'data-id' ),
image_id = jQuery( this ).attr( 'data-src' ),
_shr_media = true;
wp.media.editor.send.attachment = function( props, attachment ) {
if ( _shr_media && ( attachment.type === 'image' ) ) {
if ( image_id.indexOf( "," ) !== -1 ) {
image_id = image_id.split( "," );
$image_ids = '';
jQuery.each( image_id, function( key, value ) {
if ( $image_ids )
$image_ids = $image_ids + ',#' + value;
else
$image_ids = '#' + value;
} );
var current_element = jQuery( $image_ids );
} else {
var current_element = jQuery( '#' + image_id );
}
jQuery( '#' + textbox_id ).val( attachment.id );
console.log(textbox_id)
current_element.attr( 'src', attachment.url ).show();
} else {
alert( 'Please select a valid image file' );
return false;
}
}
wp.media.editor.open( button );
return false;
} );
} );
Now, add noth scripts in admin as follows.
function shr_add_admin_scripts(){
wp_enqueue_media();
wp_enqueue_script('shr-uploader', get_stylesheet_directory_uri().'/js/uploader.js', array('jquery'), false, true );
}
add_action('admin_enqueue_scripts', 'shr_add_admin_scripts');
Please note that uploader.js is saved in js folder in this theme, so you have to apply correct path of according to location of uploader.js in your theme.
Step 2: Adding uploder button to edit profile page.
function shr_extra_profile_fields( $user ) {
$profile_pic = ($user!=='add-new-user') ? get_user_meta($user->ID, 'shr_pic', true): false;
if( !empty($profile_pic) ){
$image = wp_get_attachment_image_src( $profile_pic, 'thumbnail' );
} ?>
<table class="form-table fh-profile-upload-options">
<tr>
<th>
<label for="image"><?php _e('Main Profile Image', 'shr') ?></label>
</th>
<td>
<input type="button" data-id="shr_image_id" data-src="shr-img" class="button shr-image" name="shr_image" id="shr-image" value="Upload" />
<input type="hidden" class="button" name="shr_image_id" id="shr_image_id" value="<?php echo !empty($profile_pic) ? $profile_pic : ''; ?>" />
<img id="shr-img" src="<?php echo !empty($profile_pic) ? $image[0] : ''; ?>" style="<?php echo empty($profile_pic) ? 'display:none;' :'' ?> max-width: 100px; max-height: 100px;" />
</td>
</tr>
</table><?php
}
add_action( 'show_user_profile', 'shr_extra_profile_fields' );
add_action( 'edit_user_profile', 'shr_extra_profile_fields' );
add_action( 'user_new_form', 'shr_extra_profile_fields' );
In above code, show_user_profile, edit_user_profile and user_new_form hooks are used to add upload button, so that button will be visible to existing user’s profile page as well as when creating new users.
Input button is to open WordPress media uploader on click.
Input hidden field is to store attachment id of insersted or selected image from media uploader of WordPress.
Step 3: Save the attachment image id to usermeta table in WordPress.
Usermeta table in WordPress is to store extra information related to user, here we will store attachment id of image for the user. Using that attachment id we can fetch all the data of concerned image.
For saving attachment id we will use profile_update and user_register hooks which will be fired when any new user is created or existing user is updated.
function shr_profile_update($user_id){
if( current_user_can('edit_users') ){
$profile_pic = empty($_POST['shr_image_id']) ? '' : $_POST['shr_image_id'];
update_user_meta($user_id, 'shr_pic', $profile_pic);
}
}
add_action('profile_update', 'shr_profile_update');
add_action('user_register', 'shr_profile_update');
That’s it and you have successfully added profile pic uploader button to profile page in dashboard of WordPress.
Reference: http://sharethingz.com/wordpress/custom-user-avatar-in-wordpress/
Inorder to change the Profile Photo of the users in the admin panel of WordPress the plugin usage is the best and easy option.
Custom User Profile Photo
Add a customized User Profile photo to a WordPress user profile
https://wordpress.org/plugins/custom-user-profile-photo/
WP User Avatar
Use any image from your WordPress Media Library as a custom user avatar. Add your own Default Avatar.
https://wordpress.org/plugins/wp-user-avatar/
Try This code and put in function.php file
add_filter( 'avatar_defaults', 'wpb_new_gravatar' );
function wpb_new_gravatar ($avatar_defaults) {
$myavatar = 'http://pngimages.net/sites/default/files/user-png-image-15189.png';
$avatar_defaults[$myavatar] = "Default Gravatar";
return $avatar_defaults;
}
currently I try to include the wordpress media library within my plugin, but the url of the image is not copied into the respective input-field. When I debug the code and include alert(image_url); I get an "Undefined".
Does anybody know what I am doing wrong here? My code follows:
JS:
jQuery(document).ready(function() {
jQuery('#upload_logo_button').click(function() {
tb_show('Upload a logo', 'media-upload.php?referer=clb_plugin_options&type=image&TB_iframe=true&post_id=0', false);
window.send_to_editor = function(html) {
var image_url = $('img',html).attr('src');
jQuery('#clb_setting_logo').val(image_url);
tb_remove();
};
return false;
});
});//jquery document
PHP:
public function admin_enqueue_scripts_func() {
wp_enqueue_script('jquery');
wp_enqueue_script('thickbox');
wp_enqueue_script('media-upload');
wp_register_script( 'js-script-clb-admin', plugins_url( 'js/clb-admin-min.js', dirname(__FILE__) ), array('jquery','media-upload','thickbox'));
wp_enqueue_script( 'js-script-clb-admin');
}//function admin_enqueue_scripts_func
add_action( 'admin_enqueue_scripts', 'admin_enqueue_scripts_func' );
HTML:
<input type="text" id="clb_setting_logo" name="clb_plugin_options[clb_setting_logo]" value="<?php echo esc_url( $options['clb_setting_logo'] ); ?>" />
<input id="upload_logo_button" type="button" class="button" value="<?php _e( 'Upload Logo', 'clb' ); ?>" />
First off, Add wp_enqueue_media(); to admin_enqueue_scripts_func(). Try that for starters, as you are doing things very differently to what I have done recently (which works).
But from what I can tell, you use var image_url = $('img',html).attr('src');, but I don;t see
As a source of reference, here is my js.
var custom_uploader;
$(document.body).on('click', '#upload_image_button' ,function(e)
{
e.preventDefault();
if (custom_uploader)
{
custom_uploader.open();
return;
}
custom_uploader = wp.media.frames.file_frame = wp.media(
{
title: 'Choose Image',
button: {
text: 'Choose Image'
},
multiple: false
});
custom_uploader.on('select', function()
{
attachment = custom_uploader.state().get('selection').first().toJSON();
$('#upload_image').val(attachment.url);
});
custom_uploader.open();
});
Perhaps try this, replacing the id's with those of your own.
Hope this helps a tad.
I have spent 3 hours, so maybe someone needs the solution. So I answered the question on my own.
<?php echo media_buttons(); ?>
<input id="category_image" type="hidden" size="100" name="category_meta[category_image]" value="" />
<div id="category_image_preview"></div>
<script>
(function( $ ) {
window.send_to_editor = function ( imgHtml ) {
$( '#category_image_preview' ).html( imgHtml )
var imgUrl = $( 'img', imgHtml ).attr( 'src' );
$( '#category_image' ).val( imgUrl );
tb_remove();
};
})( jQuery );
</script>