<?php
// Add settings page for setting parliamentary dossier image on frontpage
add_action('admin_menu', 'register_parliamentary_dossier_settings_page');
function register_parliamentary_dossier_settings_page() {
add_submenu_page(
'options-general.php',
__('Parliamentary Dossier Settings', 'astra-child'),
__('Parliamentary Dossier', 'astra-child'),
'manage_options',
'media-selector',
'parliamentary_dossier_settings_page_callback'
);
}
// Settings page callback
function parliamentary_dossier_settings_page_callback() {
// Save attachment ID
if (
isset($_POST['submit_image_selector']) &&
isset($_POST['image_attachment_id'])
) {
update_option(
'parliamentary_dossier_attachment_id',
absint($_POST['image_attachment_id'])
);
}
wp_enqueue_media();
printf(
'<h1>%1$s</h1>
<h2 style="font-size: 20px;">%2$s</h2>
<form method="post">
<div class="image-preview-wrapper" style="margin-bottom:15px;">
<img id="image-preview" src="%3$s" height="400">
</div>
<input id="upload_image_button" type="button" class="button" value="%4$s" />
<input type="hidden" name="image_attachment_id" id="image_attachment_id" value="%5$s">
<input type="submit" name="submit_image_selector" value="%6$s" class="button-primary">
<p>%7$s</p>
</form>',
esc_html__('Parliamentary Dossier', 'astra-child'),
esc_html__('Frontpage Image', 'astra-child'),
esc_html(wp_get_attachment_url(get_option('parliamentary_dossier_attachment_id'))),
esc_html__('Upload image', 'astra-child'),
esc_html(get_option('parliamentary_dossier_attachment_id')),
esc_html__('Save', 'astra-child'),
esc_html__('Recommended resolution: 356x659.', 'astra-child')
);
}
// Load media uploader script
add_action('admin_footer', 'parliamentary_dossier_print_scripts');
function parliamentary_dossier_print_scripts() {
$my_saved_attachment_post_id = get_option('parliamentary_dossier_attachment_id', 0);
?>
<script type="text/javascript">
jQuery(document).ready(function ($) {
var file_frame;
var wp_media_post_id = wp.media.model.settings.post.id;
var set_to_post_id = <?php echo (int) $my_saved_attachment_post_id; ?>;
$('#upload_image_button').on('click', function (event) {
event.preventDefault();
if (file_frame) {
file_frame.uploader.uploader.param('post_id', set_to_post_id);
file_frame.open();
return;
}
wp.media.model.settings.post.id = set_to_post_id;
file_frame = wp.media.frames.file_frame = wp.media({
title: 'Select an image to upload',
button: {
text: 'Use this image'
},
multiple: false
});
file_frame.on('select', function () {
var attachment = file_frame.state().get('selection').first().toJSON();
$('#image-preview').attr('src', attachment.url).css('width', 'auto');
$('#image_attachment_id').val(attachment.id);
wp.media.model.settings.post.id = wp_media_post_id;
});
file_frame.open();
});
$('a.add_media').on('click', function () {
wp.media.model.settings.post.id = wp_media_post_id;
});
});
</script>
<?php
}//
