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

Ray*_*ger 2 php sql wordpress orders woocommerce

我可以使用以下命令添加订单注释(私人注释):

$order->add_order_note($info_for_order);
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试使用以下方法在某些页面中获取值时:

get_comments(['post_id' => $order_id])
// or
$order_object->get_customer_order_notes()
Run Code Online (Sandbox Code Playgroud)

它只是返回一个空数组。我用谷歌搜索,但我找不到做到这一点的方法。

Loi*_*tec 5

订单注释(私人注释)仅在使用get_comments()功能时才可用于后端。
如果您查看WC_Comments exclude_order_comments()方法,您会看到针对私人订购单的前端查询已被过滤…

因此,解决方法是构建一个自定义函数以获取私有Order注释:

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;
}
Run Code Online (Sandbox Code Playgroud)

代码在您的活动子主题(或主题)的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>';
}
Run Code Online (Sandbox Code Playgroud)

  • 很好,我什至不知道如何获取该信息。哈哈 (2认同)
  • @RaymondGoldmanSeger 我是 woocommerce 数据库间谍……这就是原因。我认为也可以使用新方法扩展 WC_Order 类,但更复杂,必须在插件上完成。 (2认同)

yar*_*www 5

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

例子:

wc_get_order_notes([
   'order_id' => $order->get_id(),
   'type' => 'customer',
]);
Run Code Online (Sandbox Code Playgroud)

结果

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
        )

)
Run Code Online (Sandbox Code Playgroud)