我正在寻找一种在另一个页面上显示最后订购的产品的方法。
我认为可以在函数中创建一个短代码,该函数获取订单详细信息并在我添加短代码的任何位置显示它们。
但我似乎不知道如何让它发挥作用。到目前为止,我得到了可以使用的信息:
add_shortcode( 'displaylast', 'last' );
function last(){
$customer_id = get_current_user_id();
$order = wc_get_customer_last_order( $customer_id );
return $order->get_order();
}
[displaylast]
目前正在向我展示注释。当我将 get_order()
更改为 get_billing_first_name()
时,它确实有效。
显示订单名称。但我似乎无法得到购买的元素。也许有一个我没有看到的 get_()
?
最佳答案
您已经很接近了,但是您必须从订单对象中获取最后一个产品。
所以你得到:
function last() {
// Not available
$na = __( 'N/A', 'woocommerce' );
// For logged in users only
if ( ! is_user_logged_in() ) return $na;
// The current user ID
$user_id = get_current_user_id();
// Get the WC_Customer instance Object for the current user
$customer = new WC_Customer( $user_id );
// Get the last WC_Order Object instance from current customer
$last_order = $customer->get_last_order();
// When empty
if ( empty ( $last_order ) ) return $na;
// Get order items
$order_items = $last_order->get_items();
// Latest WC_Order_Item_Product Object instance
$last_item = end( $order_items );
// Get product ID
$product_id = $last_item->get_variation_id() > 0 ? $last_item->get_variation_id() : $last_item->get_product_id();
// Pass product ID to products shortcode
return do_shortcode("[product id='$product_id']");
}
// Register shortcode
add_shortcode( 'display_last', 'last' );
简码用法
在现有页面中:
[display_last]
或者在 PHP 中:
echo do_shortcode('[display_last]');
关于wordpress - 如何通过短代码在 WooCommerce 中显示最后订购的产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70505156/