嗨,我需要从每个订单中获取产品ID,产品变体ID和自定义字段文本。我已经检索了除自定义字段文本输入数据以外的所有内容,使用
$product_description = get_post_meta($item['product_id'])->post_content
实际上完全崩溃了网站,而所有其他参数都运行良好。请参阅下面的代码段:
add_action('woocommerce_payment_complete', 'custom_process_order', 10, 1);
function custom_process_order($order_id)
{
$order = new WC_Order( $order_id );
$myuser_id = (int)$order->user_id;
$user_info = get_userdata($myuser_id);
$items = $order->get_items();
foreach ($items as $item)
{
$product_name = $item['name'];
$product_id = $item['product_id'];
$product_variation_id = $item['variation_id'];
$product_description = get_post_meta($item['product_id'])->post_content
}
return $order_id;
}
我可能会失踪什么?
/**
*
* @param int $post_id
* @return string
*/
function get_the_content_by_id ( $post_id ) {
$content_post = get_post ( $post_id );
$content = $content_post->post_content;
$content = apply_filters ( 'the_content', $content );
$content = str_replace ( ']]>', ']]>', $content );
return $content;
}
在function.php
中添加此代码,并使用这样的方法
$product_description = get_the_content_by_id($item['product_id']);
所以你的代码看起来像
add_action('woocommerce_payment_complete', 'custom_process_order', 10, 1);
function custom_process_order($order_id) {
$order = new WC_Order ( $order_id );
$myuser_id = ( int ) $order->user_id;
$user_info = get_userdata ( $myuser_id );
$items = $order->get_items ();
foreach ( $items as $item ) {
$product_name = $item ['name'];
$product_id = $item ['product_id'];
$product_variation_id = $item ['variation_id'];
$product_description = get_the_content_by_id($item['product_id']);
}
return $order_id;
}
您错误地使用get_post_meta
。如果您想拥有post_content,那么您需要将代码更改为可能适用于您的代码:
add_action('woocommerce_payment_complete', 'custom_process_order', 10, 1);
function custom_process_order($order_id) {
$order = new WC_Order( $order_id );
$myuser_id = (int)$order->user_id;
$user_info = get_userdata($myuser_id);
$items = $order->get_items();
foreach ($items as $item) {
$product_name = $item['name'];
$product_id = $item['product_id'];
$product_variation_id = $item['variation_id'];
$product_description = get_post_field('post_content', $product_id);
}
return $order_id;
}
如果您有任何疑问,请告诉我。
游戏的后期,但对于遇到这种情况并且仍然需要答案的任何人来说:
要获取您为结帐页面创建的自定义字段,例如,询问买方的雇主,您可以通过以下方式检索信息:
$employer = get_post_meta($order_id, "field_name", true);
其中“field_name”是wp_postmeta表中的meta_key。
这适用于添加到产品的自定义字段:
$custom_field = get_post_meta($product_id, "field_name", true);