A while ago I did an explanatory tutorial on our WYCAN site to link a file ID uploaded in the media to a WooCommerce order status, however you had to tweak some code and not everyone is up to it. comfortable with it!
So I decided to make a plugin, very simple and which does the job, to allow you to select a file of your choice in the back office via the WordPress media, then to select an order status.
Once done, your file will be automatically sent to your customers based on the order status you have chosen.
This can be practical to attach your C.G.V for example (or any other document / file)
Josselyn jayant & WYCAN
*/
// Ajouter un sous-menu à l'onglet WooCommerce
add_action('admin_menu', 'woo_cgv_menu');
function woo_cgv_menu() {
add_submenu_page('woocommerce', 'CGV', 'CGV', 'manage_options', 'woo-cgv', 'woo_cgv_page_callback');
}
function woo_cgv_page_callback() {
$option_name = 'woo_cgv_file_id';
$order_status_option_name = 'woo_cgv_order_status';
if(isset($_POST['submit'])) {
if(isset($_POST['media_attachment_id'])) {
update_option($option_name, absint($_POST['media_attachment_id']));
}
if(isset($_POST['order_status'])) {
update_option($order_status_option_name, sanitize_text_field($_POST['order_status']));
}
}
if(isset($_POST['delete_file'])) {
delete_option($option_name);
}
$media_id = get_option($option_name);
$selected_status = get_option($order_status_option_name);
echo ' ';
}
function woo_cgv_admin_scripts() {
wp_enqueue_media();
wp_enqueue_script('woo-cgv-media-upload', plugins_url('media-upload.js', __FILE__), array('jquery'));
}
add_action('admin_enqueue_scripts', 'woo_cgv_admin_scripts');
// Ajout du CGV à l'e-mail en fonction de l'état de la commande
add_filter('woocommerce_email_attachments', 'attach_cgv_to_email', 10, 3);
function attach_cgv_to_email($attachments, $email_id, $order) {
$status = 'wc-' . $order->get_status();
$allowed_status = get_option('woo_cgv_order_status');
$media_id = get_option('woo_cgv_file_id');
if ($media_id && $status == $allowed_status && 'customer_' . $status . '_order' == $email_id) {
$attachments[] = get_attached_file($media_id);
}
return $attachments;
}
?>
jQuery(document).ready(function($){
var mediaUploader;
$('#upload_image_button').click(function(e) {
e.preventDefault();
if (mediaUploader) {
mediaUploader.open();
return;
}
mediaUploader = wp.media.frames.file_frame = wp.media({
title: 'Choose File',
button: {
text: 'Choose File'
}, multiple: false });
mediaUploader.on('select', function() {
var attachment = mediaUploader.state().get('selection').first().toJSON();
$('#media_attachment_id').val(attachment.id);
});
mediaUploader.open();
});
});