【问题标题】:How to display the last ordered product in WooCommerce via a shortcode如何通过短代码在 WooCommerce 中显示最后订购的产品
【发布时间】:2022-01-26 23:45:03
【问题描述】:

我正在寻找一种在另一个页面上显示最后订购的产品的方法。

我认为有可能在函数中创建一个简码,用于获取订单详细信息并在我添加简码的任何位置显示它们。


但我似乎无法弄清楚如何让它工作。到目前为止,我得到了这些信息:

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_()

【问题讨论】:

    标签: wordpress woocommerce product shortcode orders


    【解决方案1】:

    您已关闭,但是您必须从订单对象中获取最后一个产品。

    所以你得到:

    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]');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多