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);
Related
I need to add a users from WordPress backend. So, I want to generate unique User IDs for them. But I can achieve it. Can somebody help me out on this.
Here is what I cam so far. It is better if I could append the WordPress default generated unique user id to end of my field.
// Customize the user fields
function custom_user_profile_fields($user) {
$rand = randomGen(1000,5000,1);
$auth_Token = '2021-ABCD-'.$rand[0];
?>
<h3>Profile Information</h3>
<table class="form-table">
<tr>
<th><label for="srn">Student Registration Number</label></th>
<td>
<input type="text" class="regular-text" name="srn" value="<?php echo (get_option('srn') ? esc_attr( get_the_author_meta( 'srn', $user->ID ) ) : $auth_Token); ?>" id="srn" readonly /><br />
</td>
</tr>
</table>
<?php
}
add_action( 'show_user_profile', 'custom_user_profile_fields' );
add_action( 'edit_user_profile', 'custom_user_profile_fields' );
add_action( "user_new_form", "custom_user_profile_fields" );
function save_custom_user_profile_fields($user_id) {
# again do this only if you can
if(!current_user_can('manage_options'))
return false;
# save my custom field
update_usermeta($user_id, 'srn', $_POST['srn']);
}
add_action('user_register', 'save_custom_user_profile_fields');
add_action('profile_update', 'save_custom_user_profile_fields');
When a user added I can't get the previously saved Index Number to the field. It's generating another and showing again. As I am not an expert for this, could anybody help me out with this?
Thanks in advance
You were on the right path to solve the problem, but you made some mistakes.
You can use the working code below:
Creation of fields
add_action( 'user_new_form', 'bks_add_student_reg_number_field' );
add_action( 'edit_user_profile', 'bks_add_student_reg_number_field' );
add_action( 'show_user_profile', 'bks_add_student_reg_number_field' );
function bks_add_student_reg_number_field( $user ) {
?>
<h3><?php _e("Extra profile information", "blank"); ?></h3>
<table class="form-table">
<tr>
<th><label for="student_reg_number"><?php _e("Student Registration Number"); ?></label></th>
<td>
<?php if (is_object($user)) { ?>
<input type="text" name="student_reg_number" id="student_reg_number" value="<?php echo esc_attr( get_the_author_meta( 'student_reg_number', $user->ID )); ?>" class="regular-text" readonly disabled="disabled"/><br />
<?php } else { ?>
<input type="text" name="student_reg_number" id="student_reg_number" class="regular-text" /><br />
<span class="description"><?php _e("Please enter Student registration number."); ?></span>
<?php } ?>
</td>
</tr>
</table>
<?php }
This creates a field option at new user generation and edit form.
The field is only enabled when a new user is created. If the registered user has already have a value the value would be shown with no access to change it.
Save field value
add_action( 'user_register', 'bks_student_reg_number_field' );
function bks_student_reg_number_field($user_id) {
// You can maybe add checks here whch would determine if the users role is customer
// or not or maybe validate the number.
if(!current_user_can('manage_options'))
return false;
$reg_value = get_user_meta($user_id, 'student_reg_number', true);
if (isset( $_POST['student_reg_number']) && $_POST['student_reg_number'] !== $reg_value) {
update_user_meta($user_id, 'student_reg_number', $_POST['student_reg_number'].'-'.$user_id);
}
}
Only user_register hook is used to prevent updation on profile edit.
You can see the user_id appended with a - infront of it in the field and the field is readonly and disabled.
If you want user to be able to edit the id after registering as well then. do the following.
Add profile_update hook. add_action( 'profile_update', 'bks_student_reg_number_field' ); as well so that the code runs when you update the user as well.
Remove readonly and disabled attribute from the form.
The code is TESTED and WORKS.
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'm new to creating wordpress plugin. I want to create a plugin that display custom page option under setting options of wp-admin section and to save the value of input data and retrieve it, I have gone through the tutorial of otto press
I created a folder in wp-content/plugin/ named new-setting-plugin inside the folder is a file named new-setting-plugin.php so the entire file path is wp-content/plugin/new-setting-plugin/new-setting-plugin.php
the code of the file new-setting-plugin.php is given at the end of the table. After creating the code I went onto plugin page of wp-admin and installed the plugin, it was all fine.
Now when i press "Save setting" button it shows the message "Setting saved" but i can't see the value inside the input fields
I'm attaching my images to preview what it is appearing in my plugin page
When go to the plugin page i see the following input fields:
Now I'm entering the value to input fields:
When I clicked the "Save Setting" button i got the following message after page refreshed
Here is my code
<?php
add_action('admin_menu', 'add_page');
if ( !function_exists( 'add_page' ) ) {
//function to add page under setting options in wordpress admin section
function add_page() {
add_options_page('New Setting Page', 'New Setting', 'manage_options', 'plugin', 'plugin_options_frontpage');
}
}
function plugin_options_frontpage() {
?>
<div class="wrap">
<?php screen_icon('users'); ?><h2>New Setting Page title</h2>
<form action="options.php" method="post">
<?php settings_fields('plugin_options'); ?>
<?php do_settings_sections('plugin'); ?>
<table class="form-table">
<tr valign="top">
<td colspan="2">
<input name="Submit" type="submit" class="button button-primary" value="<?php esc_attr_e('Save Changes'); ?>" />
</td>
</tr>
</table>
</form>
</div>
<?php
}
add_action('admin_init', 'plugin_admin_init');
function plugin_admin_init(){
register_setting( 'plugin_options', 'plugin_options', 'plugin_options_validate' );
add_settings_section('plugin_main', 'Main Settings', 'plugin_section_text', 'plugin');
add_settings_field('plugin_text_input1', 'Input 1', 'plugin_input1', 'plugin', 'plugin_main');
add_settings_field('plugin_text_input2', 'Input 2', 'plugin_input2', 'plugin', 'plugin_main');
}
function plugin_section_text() {
echo '<p>New input setting to be saved.</p>';
}
function plugin_input1() {
$options = get_option('plugin_options');
echo "<input id='plugin_input1' class='normal-text code' name='plugin_options[text_string]' size='30' type='text' value='{$options['text_string']}' />";
}
function plugin_input2() {
$options = get_option('plugin_options');
echo "<input id='plugin_input2' class='normal-text code' name='plugin_options[text_string]' size='30' type='text' value='{$options['text_string']}' />";
}
function plugin_options_validate($input) {
$options = get_option('plugin_options');
$options['text_string'] = trim($input['text_string']);
if(!preg_match('/^[a-z0-9]{32}$/i', $options['text_string'])) {
$options['text_string'] = '';
}
return $options;
}
?>
What wrong in my code, How can I correct my code and is there a way to show the value of input fields outside the field in same page in a table?
You won't see them there. You have to get_options.
For your code, if you do var_export( get_option('plugin_options') ); you'll see those saved settings/values.
check the validation criteria.
preg_match('/^[a-z0-9]{32}$/i', $options['text_string'])
Comment the code inside validation function and test.
function plugin_options_validate($input) {
$options = get_option('plugin_options');
//$options['text_string'] = trim($input['text_string']);
//if(!preg_match('/^[a-z0-9]{32}$/i', $options['text_string'])) {
//$options['text_string'] = '';
//}
return $options;
}
You have to change the 'name' of the inputs :
function manage_lists_cc_input1() {
$options = get_option('manage_lists_cc_options');
echo "<input id='manage_lists_cc_input1' class='normal-text code' name='manage_lists_cc_options[0]' size='30' type='text' value='{$options['text_string_0']}' />";
}
function manage_lists_cc_input2() {
$options = get_option('manage_lists_cc_options');
echo "<input id='manage_lists_cc_input2' class='normal-text code' name='manage_lists_cc_options[1]' size='30' type='text' value='{$options['text_string_1']}' />";
And just change the validate script to get the values (this is a simple example without validation ) :
function manage_lists_cc_options_validate($input) {
$options['text_string_0'] = $input[0];
$options['text_string_1'] = $input[1];
return $options;
}
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>