首页 > 解决方案 > 如何从 wordpress 中的 woocommerce 订单中的附加信息中获取文件?

问题描述

我正在尝试获取 woocommerce 订单中包含的文件的内容(我想是),虽然我熟悉 PHP,但我不知道如何使用 wordpress,所以如果这有一个明显的解决方案,我深表歉意。

我添加了这个额外的字段,要求myfield2通过 WooCheckout 上传文件。该文件仅包含一个json对象。还有一个名为的字段myfield1,它只是一个下拉选择的字符串值,我觉得很好。

这是我最接近的平底锅:

<?PHP
$some_order_number = "869";
echo "<br>-----------------------------------<br>";
$order = get_post_meta( $some_order_number );
var_dump($order);
echo "<br>-----------------------------------<br>";
var_dump($order["myfield1"]);
echo "<br>-----------------------------------<br>";
var_dump($order["myfield2"]);
?>

我在结果页面上看到的是:

array(47) { <...All the order details (name, address, ordered item etc)...> } 
"-----------------------------------------"
array(1) { [0]=> string(11) "Three times" } 
"-----------------------------------------"
array(1) { [0]=> string(4) "895," }

我该如何处理这个"895,"值?它是某个地方的身份证号码吗?还是我以错误的方式解决这个问题?

标签: phpwordpresswoocommerce

解决方案


在浏览了 WooCommerce 的文档之后,我发现了一些有用的东西!我不能保证这是最有效的方法,但它确实有效。

<?PHP

// Get the file's field name
// Known as "abbreviation" on WooCheckout
$file_field_name = 'myfield2';

// Get the order number. (could use wc_get_orders() )
$order_id = "896";

// Get the order object for this order id
$order = wc_get_order( $order_id );

// Get the attachment ID.
$attachment_id = $order->get_meta($file_field_name);

// Get the properties of this attachment
$props = wc_get_product_attachment_props( $attachment_id );

// Select the URL from the properties
$file_url = $props["url"];

// Download the file data from this url.
$file_data = file_get_contents($file_url);

// ...now we do stuff with the file contents.
echo "file contents: <br>";
var_dump($file_data);

?>

..这里是一个单一的功能,用于复制和粘贴。

/**
 * Given the order object and the file's field name,
 * get the file contents from the uploaded content.
 */
function get_order_file($order, $field_name){
    $attachment_id = $order->get_meta($field_name);
    $props = wc_get_product_attachment_props( $attachment_id );
    $file_data = file_get_contents($props["url"]);
    return $file_data;
}

推荐阅读