从Woocommerce订单/ WC_Order对象获取订单备注?

时间:2017-04-18 03:44:57

标签: php sql wordpress woocommerce orders

我可以添加订单备注(私人备注):

$order->add_order_note($info_for_order);

但是当我试图通过以下方式获取某些页面中的值时:

get_comments(['post_id' => $order_id])
// or
$order_object->get_customer_order_notes()

它只返回一个空数组。我google了这个,我找不到这样做的方法。

3 个答案:

答案 0 :(得分:4)

  

订单备注(私密备注)仅适用于使用 get_comments() 功能的后端。
如果您查看WC_Comments exclude_order_comments()方法,您会看到有关私人订单备注的前端查询已被过滤...

所以转向是建立一个自定义函数来获取私人订单备注:

function get_private_order_notes( $order_id){
    global $wpdb;

    $table_perfixed = $wpdb->prefix . 'comments';
    $results = $wpdb->get_results("
        SELECT *
        FROM $table_perfixed
        WHERE  `comment_post_ID` = $order_id
        AND  `comment_type` LIKE  'order_note'
    ");

    foreach($results as $note){
        $order_note[]  = array(
            'note_id'      => $note->comment_ID,
            'note_date'    => $note->comment_date,
            'note_author'  => $note->comment_author,
            'note_content' => $note->comment_content,
        );
    }
    return $order_note;
}

代码放在活动子主题(或主题)的function.php文件中,或者放在任何插件文件中。

此代码经过测试并有效。

用法 (例如$order_id = 6238

$order_id = 6238;
$order_notes = get_private_order_notes( $order_id );
foreach($order_notes as $note){
    $note_id = $note['note_id'];
    $note_date = $note['note_date'];
    $note_author = $note['note_author'];
    $note_content = $note['note_content'];

    // Outputting each note content for the order
    echo '<p>'.$note_content.'</p>';
}

答案 1 :(得分:3)

获得订单备注还有其他最佳方式。

/**
 * Get all approved WooCommerce order notes.
 *
 * @param  int|string $order_id The order ID.
 * @return array      $notes    The order notes, or an empty array if none.
 */
function custom_get_order_notes( $order_id ) {
    remove_filter( 'comments_clauses', array( 'WC_Comments', 'exclude_order_comments' ) );
    $comments = get_comments( array(
        'post_id' => $order_id,
        'orderby' => 'comment_ID',
        'order'   => 'DESC',
        'approve' => 'approve',
        'type'    => 'order_note',
    ) );
    $notes = wp_list_pluck( $comments, 'comment_content' );
    add_filter( 'comments_clauses', array( 'WC_Comments', 'exclude_order_comments' ) );
    return $notes;
}

答案 2 :(得分:2)

有woo文档https://docs.woocommerce.com/wc-apidocs/function-wc_get_order_notes.html

示例:

wc_get_order_notes([
   'order_id' => $order->get_id(),
   'type' => 'customer',
]);

结果

Array
(
    [0] => stdClass Object
        (
            [id] => 11
            [date_created] => WC_DateTime Object
                (
                    [utc_offset:protected] => 3600
                    [date] => 2019-03-21 11:38:51.000000
                    [timezone_type] => 1
                    [timezone] => +00:00
                )

            [content] => Hi, blah blah blah
            [customer_note] => 1
            [added_by] => admin
        )

)