php 上传图像到WooCommerce通过HTML表单作为元数据

2sbarzqh  于 2023-10-15  发布在  PHP
关注(0)|答案(2)|浏览(131)

我已经成功地构建了一个表单,它允许用户输入他们的订单ID、费用金额和费用原因。当用户提交表单时,费用和费用原因被添加到提交的订单ID的元数据中。
下面是整个代码:

<form id="expense_form" class="expense_form" action="" method="post">
    <label for="order-id">Order ID:</label>
    <input class="exp_order_no" id="exp_order_no" type="text" pattern="[0-9]*" placeholder="Enter the Order Number" required>
    
    <label for="expense">Expense:</label>
    <input class="expense_amt" id="expense_amt" type="text"  pattern="[0-9]*" placeholder="Enter the expense amount" required>
    
    <label for="reason">Reason for Expense:</label>
    <textarea class="expense_reason" id="expense_reason" id="reason" name="reason" rows="4" placeholder="Enter Message" required></textarea>

    <input type="submit" class="exp_but" id="exp_but" value="Submit">
</form> 
<script>
    jQuery(document).ready(function($) {
            $('#expense_form').on('submit', function(e) {
                e.preventDefault();
                var orderid  = $('#exp_order_no').val();
                var expense  = $('#expense_amt').val();
                var expense_reason  = $('#expense_reason').val();
                    //  console.log (orderid);
                    //  console.log (expense);
                    //  console.log (expense_reason);
             $.ajax({
                    url: '<?php echo admin_url('admin-ajax.php'); ?>',
                    type: 'POST',
                    data: {
                        action:'update_custom_field_order_expense_php',
                        orderid: orderid,
                        expense: expense,
                        expense_reason:expense_reason
                    },
                    success: function( response ) {
                        console.log( 'Custom field updated successfully.' );
                        alert('Expense Submitted Successfully !!');
                        location.reload();
                    },
                    error: function( response ) {
                        console.log( 'Failed to Submit Expense.' );
                        alert('Failed to Submit Expense. Contact Online Team.');
                        location.reload();
                    }
                });
             });
        });         
</script>

<?php

add_action( 'wp_ajax_update_custom_field_order_expense_php', 'update_custom_field_order_expense_php' );
add_action('wp_ajax_nopriv_update_custom_field_order_expense_php', 'update_custom_field_order_expense_php');

function update_custom_field_order_expense_php() {
    $order_id = $_POST['orderid'];
    $order_expense = $_POST['expense'];
    $order_expense_reason = $_POST['expense_reason'];
    $order = wc_get_order( $order_id );
    if ( is_user_logged_in()) {
        $current_user = wp_get_current_user();
        $current_user_id = $current_user->ID;
    
        $driver_id = get_post_meta($order_id, 'lddfw_driverid', true);
        //$current_date = date_i18n( 'j F, Y', strtotime( $current_date_time ) );
        foreach ( $order->get_meta_data() as $meta ) {
                            if ( $meta->key === 'Driver Expense') {
                $expense_exist=$meta->value;
                }
        }
         if (($current_user_id == $driver_id) && (empty($expense_exist)))  {
            $order->update_meta_data('Driver Expense', $order_expense);
            $order->update_meta_data('Driver Expense Reason', $order_expense_reason);
            $order->save();
            wp_send_json_success();
        } else {
            http_response_code(403);
            wp_send_json(array('error' => 'Access denied'));
        }
    } else {
        http_response_code(401); 
        wp_send_json(array('error' => 'Authentication required'));
    }
    exit;
}
    ?>

然而,我现在面临着一个增加重要功能的挑战:上传图片作为费用证明。

**图像上传的费用证明:**我希望用户能够上传图像作为他们的费用证明。这对于核查和记录保存至关重要。理想情况下,用户应该能够附加一个或多个与其费用相关的图像。

我不知道从哪里开始实现这个功能。如果有人有经验或建议如何实现这一点,我将非常感谢您的指导和见解。
以下是我的一些具体问题:
如何在表单中启用图像上传?
存储这些上传的图像并将其链接到相应订单ID的最佳方式是什么?
我已经创建了一个目录/wp-content/uploads/2023/Uploads_images,并希望所有的图像都存储在这里。
任何与此功能相关的帮助或代码示例都非常有价值。提前感谢您的帮助!

moiiocjp

moiiocjp1#

更新您的表单以包含新的未输入字段:

<label for="proof_images">Proof of Expense (Image):</label>
<input type="file" id="proof_images" name="proof_images[]" accept="image/*" multiple>

修改JavaScript代码以处理文件上传沿着其他表单数据。您需要使用FormData对象通过AJAX请求将文件发送到服务器。

jQuery(document).ready(function($) {
    $('#expense_form').on('submit', function(e) {
        e.preventDefault();
        var orderid = $('#exp_order_no').val();
        var expense = $('#expense_amt').val();
        var expense_reason = $('#expense_reason').val();
        var formData = new FormData(this);

        $.ajax({
            url: '<?php echo admin_url('admin-ajax.php'); ?>',
            type: 'POST',
            data: {
                action: 'update_custom_field_order_expense_php',
                orderid: orderid,
                expense: expense,
                expense_reason: expense_reason,
            },
            processData: false, // Prevent jQuery from processing the data
            contentType: false, // Prevent jQuery from setting content type
            data: formData, // Use the FormData object
            success: function(response) {
                // Handle success
                console.log('Custom field updated successfully.');
                alert('Expense Submitted Successfully !!');
                location.reload();
            },
            error: function(response) {
                // Handle error
                console.log('Failed to Submit Expense.');
                alert('Failed to Submit Expense. Contact Online Team.');
                location.reload();
            }
        });
    });
});

然后更新update_custom_field_order_expense_php函数来处理文件上传并将其保存到所需的目录:

function update_custom_field_order_expense_php() {
    // ... Your existing code ...

    // Handle file uploads
    if (!empty($_FILES['proof_images']['name'])) {
        $upload_dir = wp_upload_dir();
        $target_dir = $upload_dir['basedir'] . '/2023/Expense_images/';

        // Create the target directory if it doesn't exist
        if (!file_exists($target_dir)) {
            wp_mkdir_p($target_dir);
        }

        $file_count = count($_FILES['proof_images']['name']);

        for ($i = 0; $i < $file_count; $i++) {
            $file_name = $_FILES['proof_images']['name'][$i];
            $file_tmp_name = $_FILES['proof_images']['tmp_name'][$i];

            // Generate a unique file name to prevent overwriting
            $unique_filename = wp_unique_filename($target_dir, $file_name);

            $target_file = $target_dir . $unique_filename;

            // Move the uploaded file to the target directory
            if (move_uploaded_file($file_tmp_name, $target_file)) {
                // You can store the file paths or URLs in your order's metadata
                // Example: $order->update_meta_data('Expense Proof Image ' . ($i + 1), $target_file);
            }
        }
    }

    // ... Your existing code ...
}

这段代码将处理多个文件上传,并将它们存储在/wp-content/uploads/2023/Uploads_images/目录中,并使用唯一的文件名。然后,您可以选择如何将这些文件路径或URL与订单元数据中的相应订单ID相关联,如代码中的注解所示。
这是一个基本的例子。但是,在实现文件上传时,重要的是要优先考虑安全性,以防止各种形式的攻击和漏洞。因此,请确保检查文件类型,大小等内容:

$allowed_mime_types = array('image/jpeg', 'image/png', 'image/gif');
if (!in_array($_FILES['proof_images']['type'][$i], $allowed_mime_types)) {
    // Handle invalid file type
}

$max_file_size = 5 * 1024 * 1024; // 5 MB
if ($_FILES['proof_images']['size'][$i] > $max_file_size) {
    // Handle oversized file
}
ldxq2e6h

ldxq2e6h2#

更新:

我试着调试代码和修复和可能的问题,但我无法通过代码片段插件激活PHP代码,因为它给我错误状态400.我给整个代码波纹管,请让我知道我如何才能解决这个问题。

<form id="expense_form" class="expense_form" action="" method="post" enctype="multipart/form-data">
   <label for="order-id">Order ID:</label>
   <input class="exp_order_no" id="exp_order_no" type="text" pattern="[0-9]*" placeholder="Enter the Order Number" required>

   <label for="expense">Expense:</label>
   <input class="expense_amt" id="expense_amt" type="text" pattern="[0-9]*" placeholder="Enter the expense amount" required>

   <label for="reason">Reason for Expense:</label>
   <textarea class="expense_reason" id="expense_reason" name="reason" rows="4" placeholder="Enter Message" required></textarea>

   <label for="my_image_upload">Upload Image:</label>
   <input type="file" name="my_image_upload[]" id="my_image_upload" accept="image/*" required multiple>

   <input type="submit" class="exp_but" id="exp_but" value="Submit">
</form>

<script>
jQuery(document).ready(function($) {
   $('#expense_form').on('submit', function(e) {
       e.preventDefault();
       var orderid = $('#exp_order_no').val();
       var expense = $('#expense_amt').val();
       var expense_reason = $('#expense_reason').val();
       var formData = new FormData(this);

       // Debugging: Output form data to console
       console.log('Order ID:', orderid);
       console.log('Expense:', expense);
       console.log('Expense Reason:', expense_reason);
       console.log('Form Data:', formData);

       $.ajax({
           url: '<?php echo admin_url('admin-ajax.php'); ?>',
           type: 'POST',
           data: formData, // Use formData to send all form data
           processData: false,
           contentType: false,
           enctype: 'multipart/form-data', // Specify enctype for file uploads
           success: function(response) {
               // Handle success
               console.log('Custom field updated successfully.');
               alert('Expense Submitted Successfully !!');
               location.reload();
           },
           error: function(response) {
               // Handle error
               console.log('Failed to Submit Expense.');
               alert('Failed to Submit Expense. Contact Online Team.');
               location.reload();
           }
       });
   });
});
</script>

add_action('wp_ajax_update_custom_field_order_expense_php', 'update_custom_field_order_expense_php');
add_action('wp_ajax_nopriv_update_custom_field_order_expense_php', 'update_custom_field_order_expense_php');

function update_custom_field_order_expense_php() {
   $order_id = sanitize_text_field($_POST['orderid']);
   $order_expense = sanitize_text_field($_POST['expense']);
   $order_expense_reason = sanitize_text_field($_POST['expense_reason']);
   $order = wc_get_order($order_id);

   if (!empty($_FILES['my_image_upload']['name'])) {
       $upload_dir = wp_upload_dir();
       $target_dir = $upload_dir['basedir'] . '/2023/Expense_images/';

       if (!file_exists($target_dir)) {
           wp_mkdir_p($target_dir);
       }

       $file_count = count($_FILES['my_image_upload']['name']);

       for ($i = 0; $i < $file_count; $i++) {
           $file_name = $_FILES['my_image_upload']['name'][$i];
           $file_tmp_name = $_FILES['my_image_upload']['tmp_name'][$i];

           $unique_filename = wp_unique_filename($target_dir, $file_name);

           $target_file = $target_dir . $unique_filename;

           if (move_uploaded_file($file_tmp_name, $target_file)) {
               $order->update_meta_data('Expense Proof Image ' . ($i + 1), $target_file);
           }
       }
   }

   $order->update_meta_data('Driver Expense', $order_expense);
   $order->update_meta_data('Driver Expense Reason', $order_expense_reason);
   $order->save();

   // Debugging: Send a JSON response
   wp_send_json_success('Expense submitted successfully.');
}

相关问题