在 WooCommerce 订单详细信息表中显示产品摘录,并据此对订单项目进行排序

问题描述 投票:0回答:1

目前我正在使用 详细订单中的 Woocommerce Short_Description 答案代码在 WooCommerce 结帐页面上显示产品摘录:

add_filter( 'woocommerce_order_item_name', 'add_single_excerpt_to_order_item', 10, 3 );
function add_single_excerpt_to_order_item( $item_name, $item, $is_visible ){
    $product_id = $item->get_product_id(); // Get the product Id
    $excerpt = get_the_excerpt( $product_id ); // Get the short description

    return $excerpt . $item_name ;
}

然后我尝试根据产品摘录按字母顺序对订单项目进行排序。通过如何按字母顺序对 WooCommerce 订单项目进行排序,我能够编写以下代码:

/*
 * Filters the $order->get_items() method results to order all line items by
 * product name
 */
add_filter( 'woocommerce_order_get_items', function( $items, $order ) {

  uasort( $items, 
          function( $a, $b ) { 
            return strnatcmp( $a['excerpt'], $b['excerpt'] ); 
          }
        );

  return $items;

}, 10, 2 );

使用此代码,我没有收到任何错误消息,但也没有得到所需的结果。有什么建议如何按字母顺序对摘录进行排序吗?

php wordpress woocommerce product orders
1个回答
1
投票

要显示简短的产品描述,您可以使用:

function filter_woocommerce_order_item_name( $item_name, $item, $is_visible ) {
    // Get the product ID
    $product_id = $item->get_product_id();

    // Get the short description
    $excerpt = get_the_excerpt( $product_id );

    // NOT empty
    if ( ! empty ($excerpt ) ) {
        return $excerpt . ' - ' . $item_name;
    }

    return $item_name;
}
add_filter( 'woocommerce_order_item_name', 'filter_woocommerce_order_item_name', 10, 3 );

注意: 因为

woocommerce_order_item_name
钩子是在多个页面(以及 WooCommerce 电子邮件通知)上执行的,所以您可以使用 条件标签


关于排序,

$a['excerpt']
不存在,可以用
get_the_excerpt( $a['product_id'] )

代替

所以你得到:

function filter_woocommerce_order_get_items( $items, $order, $types ) {
    // Sort an array with a user-defined comparison function and maintain index association
    uasort( $items, function( $a, $b ) {
        // String comparisons using a "natural order" algorithm
        return strnatcmp( get_the_excerpt( $a['product_id'] ), get_the_excerpt( $b['product_id'] ) ); 
    } );

    return $items;
}
add_filter( 'woocommerce_order_get_items', 'filter_woocommerce_order_get_items', 10, 3 );
© www.soinside.com 2019 - 2024. All rights reserved.