Call to a member function get_items() on boolean in WooCommerce thankyou

后端 未结 1 414
再見小時候
再見小時候 2021-01-24 18:55

I am trying to get order details to display a summary on my thank you page. The issue I am having is that this code snippet I have is breaking my wordpress. I have the stacktrac

相关标签:
1条回答
  • 2021-01-24 19:44

    The variable $order_id is not defined, $item->get_quantity need to be $item->get_quantity() and the output should never be echoed with a shortcode, always returned.

    This shortcode is to be used on Order received page

    add_shortcode('order_table_summary', 'display_order_table_summary_thankyou');
    
    function display_order_table_summary_thankyou(){
        global $wp;
    
        // If order_id is defined on Order reveived / thankyou page
        if ( is_wc_endpoint_url('order-received')
        && isset($wp->query_vars['order-received'])
        && absint($wp->query_vars['order-received']) > 0 ) {
    
            // Get the WC_Order Object
            $order = wc_get_order( absint($wp->query_vars['order-received']) );
    
            ob_start(); // Start buffering
    
            echo '<table><tr>
                <th>' . __("Product name", "woocommerce") . '</th>
                <th>' . __("Quantity", "woocommerce") . '</th>
                <th>' . __("Line total", "woocommerce") . '</th>
            </tr>';
    
            // Loop Over Order Items
            foreach ( $order->get_items() as $item ) {
                echo '<tr>
                <td>' . $item->get_name() . '</td>
                <td>' . $item->get_quantity() . '</td>
                <td>' . $item->get_total() . '</td>
                </tr>';
            }
    
            echo '</table>';
    
            return ob_get_clean(); // Return the buffered content
        }
    }
    

    Code goes in functions.php file of the active child theme (or active theme). Tested and works.

    USAGE:

    • [order_table_summary]
    • or also inside PHP code: echo do_shortcode('[order_table_summary]');

    Just for testing:

    add_action( 'woocommerce_thankyou', 'testing_shorcode' );
    function testing_shorcode() {
        echo do_shortcode('[order_table_summary]');
    }
    

    Related:

    • Get the Order ID in Woocommerce order received page as shortcode
    • Get Order items and WC_Order_Item_Product in WooCommerce 3
    0 讨论(0)
提交回复
热议问题