Created
August 7, 2022 16:57
-
-
Save Mamikonars/28b7a31b0fe9b96b2a02b1ed3d766b29 to your computer and use it in GitHub Desktop.
Image upload on options WP page
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
jQuery( document ).ready(function($) { | |
//image option | |
$('body').on( 'click', '.muna-upl', function(e){ | |
e.preventDefault(); | |
var button = $(this), | |
custom_uploader = wp.media({ | |
title: 'Insert image', | |
library : { | |
// uploadedTo : wp.media.view.settings.post.id, // attach to the current post? | |
type : 'image' | |
}, | |
button: { | |
text: 'Use this image' // button label text | |
}, | |
multiple: false | |
}).on('select', function() { // it also has "open" and "close" events | |
var attachment = custom_uploader.state().get('selection').first().toJSON(); | |
button.html('<img src="' + attachment.url + '">').next().show().next().val(attachment.id); | |
}).open(); | |
}); | |
// on remove button click | |
$('body').on('click', '.muna-rmv', function(e){ | |
e.preventDefault(); | |
var button = $(this); | |
button.next().val(''); // emptying the hidden field | |
button.hide().prev().html('Upload image'); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function muna_custom_settings() { | |
//options image | |
register_setting( 'muna_options_group', 'author_avatar'); | |
add_settings_section( | |
'muna_options_section', | |
esc_html__( 'Muna theme admin settings', THEME_NAME ), | |
'settings_section_cb', | |
'muna-options' | |
); | |
//options image | |
add_settings_field('author_avatar', esc_html__( 'Choose author avatar', THEME_NAME ), 'author_avatar_settings_field_cb', 'muna-options', 'muna_options_section', array('label_for' => 'author_avatar')); | |
} | |
//options image | |
function author_avatar_settings_field_cb() { | |
$image_id = get_option( 'author_avatar' ); | |
if( $image = wp_get_attachment_image_src( $image_id ) ) { | |
echo '<a href="#" class="muna-upl"><img src="' . $image[0] . '" /></a> | |
<a href="#" class="muna-rmv">Remove image</a> | |
<input type="hidden" name="author_avatar" value="' . $image_id . '">'; | |
} else { | |
echo '<a href="#" class="muna-upl">Upload image</a> | |
<a href="#" class="muna-rmv" style="display:none">Remove image</a> | |
<input type="hidden" name="author_avatar" value="">'; | |
} | |
} | |
//get image | |
$option_avatar = wp_get_attachment_image_src(get_option('author_avatar')); | |
$avatar = $option_avatar ? $option_avatar[0] : ''; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment