php - 在 WooCommerce 中调用布尔值的成员函数 get_items() 谢谢
问题描述
我正在尝试获取订单详细信息以在我的感谢页面上显示摘要。我遇到的问题是我的这个代码片段正在破坏我的 wordpress。我有堆栈跟踪,但我不确定如何修复它。对我来说,代码看起来是正确的,所以请确保它为什么不起作用。有谁知道这个堆栈跟踪的含义是什么以及我该如何解决它?
An error of type E_ERROR was caused in line 7 of the file /home4/xxx/public_html/staging/4326/wp-content/plugins/code-snippets/php/snippet-ops.php(446) : eval()'d code. Error message: Uncaught Error: Call to a member function get_items() on boolean in /home4/xxx/public_html/staging/4326/wp-content/plugins/code-snippets/php/snippet-ops.php(446) : eval()'d code:7
Stack trace:
#0 /home4/xxx/public_html/staging/4326/wp-includes/shortcodes.php(343): order_table_summary('', '', 'order_table_sum...')
#1 [internal function]: do_shortcode_tag(Array)
#2 /home4/xxx/public_html/staging/4326/wp-includes/shortcodes.php(218): preg_replace_callback('/\\[(\\[?)(order_...', 'do_shortcode_ta...', '\n
我的代码:
function order_table_summary(){
$order = wc_get_order($order_id);
// Get and Loop Over Order Items
foreach ( $order->get_items() as $item_id => $item ) {
echo $item->get_name() . $item->get_quantity. $item->get_total();
}
}
add_shortcode('order_table_summary', 'order_table_summary');
更新 添加简码
解决方案
该变量$order_id
未定义,$item->get_quantity
需要定义,$item->get_quantity()
并且输出永远不应使用简码回显,始终返回。
此简码将在收到的订单页面上使用
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
}
}
代码位于活动子主题(或活动主题)的 functions.php 文件中。测试和工作。
用法:
[order_table_summary]
- 或者在 PHP 代码中:
echo do_shortcode('[order_table_summary]');
仅用于测试:
add_action( 'woocommerce_thankyou', 'testing_shorcode' );
function testing_shorcode() {
echo do_shortcode('[order_table_summary]');
}
有关的:
推荐阅读
- reactjs - 如何使用 axios.get 方法更新反应状态?
- mysql - 正确加入mysql 8
- webmin - 使用 virtualmin 和 webmin 在 debian 9 上安装 MySQL 时出现问题
- python-3.x - 如何将 Oauth 2.0 与 google dialogflow API 集成
- regex - 正则表达式 | 如何为匹配的子字符串添加前缀?
- javascript - jQuery 找不到带有 ID 的 div
- c# - 如何在 c sharp 中检索特定格式的声明?
- webpack - 是否可以配置 webpack,以便在满足特定条件时对包的评估将提前终止?
- html - Bootstrap 3中的相等列高
- javascript - vue composition api中的反应数据未在模板中呈现