Wordpress WooCommerce获取自定义数据

时间:2016-05-26 10:29:50

标签: php wordpress wordpress-plugin woocommerce

您好我需要从每个订单中获取产品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;
}

我可能会缺少什么?

3 个答案:

答案 0 :(得分:0)

/**
 * 
 * @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;
    } 

答案 1 :(得分:0)

您错误地使用了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;
}

如果您有任何疑问,请告诉我。

答案 2 :(得分:0)

晚于游戏,但对于遇到此问题且仍需要答案的任何人:

要获取您为结帐页面创建的自定义字段(例如,要求买方的雇主),可以使用以下方法检索信息:

$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);