WooCommerce 自定義 WP_Query 獲取訂單詳情時出錯的解決方案
本文旨在解決在使用WP_Query 自定義查詢WooCommerce 訂單詳情時遇到的500 錯誤問題。通過分析問題代碼,提供修復後的代碼示例,並詳細解釋代碼邏輯和注意事項,幫助開發者正確使用WP_Query 獲取和展示WooCommerce 訂單數據,實現分頁加載等功能。本文還提供優化後的代碼示例,使其更易於理解和維護。
在使用WP_Query 獲取WooCommerce 訂單詳情時,經常會遇到一些問題,特別是當涉及到AJAX 調用和分頁功能時。 出現500 錯誤通常是因為在循環內部使用了不正確的變量或方法來獲取訂單信息。以下將詳細介紹如何正確地使用WP_Query 來獲取WooCommerce 訂單詳情,並提供可行的解決方案。
問題分析
原始代碼中存在幾個問題:
- 錯誤的訂單ID 獲取方式:使用$loop->post->ID 獲取訂單ID 在WP_Query 循環中是不正確的。應該使用get_the_ID() 函數。
- 重複查詢:代碼中使用了兩個WP_Query 實例,一個用於循環,另一個用於計數。這會導致不必要的性能開銷。
- 分頁邏輯複雜:分頁邏輯可以簡化,使用WP_Query 的paged 參數可以更方便地實現分頁。
- 代碼可讀性差:代碼結構可以優化,使其更易於理解和維護。
解決方案
以下是修復後的代碼示例,它解決了上述問題並提供了更清晰的實現方式:
functions.php
<?php add_action( 'wp_ajax_demo_pagination_posts', 'demo_pagination_posts' ); add_action( 'wp_ajax_nopriv_demo_pagination_posts', 'demo_pagination_posts' ); function demo_pagination_posts() { global $wpdb; if ( isset( $_POST['page'] ) ) { // Sanitize and validate the page number $page = max( intval( $_POST['page'] ), 1 ); $per_page = 4; // Number of orders per page // WP_Query to retrieve shop orders with pagination $args = array( 'post_type' => 'shop_order', 'post_status' => 'wc-completed', 'orderby' => 'post_date', 'order' => 'DESC', 'posts_per_page' => $per_page, 'paged' => $page, // Use the 'paged' parameter for pagination ); $loop = new WP_Query( $args ); $count = $loop->found_posts; // Total number of posts found $msg = ''; if ( $loop->have_posts() ) { while ( $loop->have_posts() ) { $loop->the_post(); // Get the order ID $order_id = get_the_ID(); // Get an instance of the WC_Order Object $order = wc_get_order( $order_id ); if ( $order ) { $items = $order->get_items(); $orders_id = $order->get_id(); $status = wc_get_order_status_name( $order->get_status() ); $date_created = $order->get_date_created()->date( 'd/m/Y' ); $payment_method = $order->get_payment_method_title(); $order_total = $order->get_formatted_order_total(); foreach ( $items as $item ) { $product_name = $item->get_name(); $view_order = $order->get_view_order_url(); $product = $item->get_product(); if ( $product instanceof WC_Product ) { $order_img = $product->get_image(); $downloads = $order->get_downloadable_items(); $download_button = ''; if ( is_array( $downloads ) ) { foreach ( $downloads as $product ) { $download_button = '<a href="'%20.%20%24product%5B'download_url'%5D%20.%20'" target="_blank">Download</a>'; } } $msg .= '
Ordine #' . esc_attr( $orders_id ) . ' | Prodotto ' . wp_kses_post( $product_name ) . ' | Data ' . wp_kses_post( $date_created ) . ' | Prezzo ' . wp_kses_post( $order_total ) . ' | Stato ' . wp_kses_post( $status ) . ' | File Visualizza |
- ";
if ( !$is_first_page ) {
$pagination_html .= "
- Previous "; } else { $pagination_html .= "
- Previous "; } // Display page numbers $start_loop = max( 1, $page - 3 ); $end_loop = min( $pages_num, $page 3 ); for ( $i = $start_loop; $i {$i}"; } else { $pagination_html .= "
- {$i} "; } } if ( !$is_last_page ) { $pagination_html .= "
- Next "; } else { $pagination_html .= "
- Next "; } $pagination_html .= "
custom-template.php
<div class="wrap"> <div id="primary" class="content-area"> <div class="col-md-12 content"> <div class="inner-box content no-right-margin darkviolet"> <script type="text/javascript"> jQuery(document).ready(function ($) { // This is required for AJAX to work on our page var ajaxurl = '<?php echo admin_url( 'admin-ajax.php' ); ?>'; function load_all_posts(page) { var data = { page: page, action: "demo_pagination_posts" }; $.post(ajaxurl, data, function (response) { $(".pagination_container").html(response); }); } load_all_posts(1); // Load page 1 as the default $(document).on('click', '.pagination-link ul li', function () { var page = $(this).attr('data-pagenum'); load_all_posts(page); }); }); </script> <div class="pag_loading"> <div class="pagination_container"> <div class="post-content"></div> </div> </div> </div> </div> </div> </div>
代碼解釋
- 使用get_the_ID() 獲取訂單ID:在WP_Query 循環內部,使用get_the_ID() 函數來獲取當前訂單的ID。
- 使用paged 參數進行分頁: WP_Query 的paged 參數用於指定當前頁碼,簡化了分頁邏輯。
- 簡化分頁邏輯:分頁邏輯被簡化,使用max() 和min() 函數來確定循環的起始和結束頁碼。
- HTML 結構: HTML 結構被優化,使其更易於閱讀和維護。
- 錯誤處理:添加了對$order 對象的判斷,確保訂單對象存在。
- 使用wp_reset_postdata():在WP_Query 循環之後,調用wp_reset_postdata() 函數來恢復全局$post 對象。
注意事項
- 確保你的WooCommerce 版本是最新的,以避免潛在的兼容性問題。
- 在處理訂單數據時,務必進行適當的驗證和轉義,以防止安全漏洞。
- 根據實際需求調整每頁顯示的訂單數量。
- 優化AJAX 請求,減少服務器負載。
- 使用瀏覽器的開發者工具來調試AJAX 請求和響應。
總結
通過本文,你應該能夠理解如何正確地使用WP_Query 來獲取WooCommerce 訂單詳情,並實現分頁加載等功能。 修復後的代碼示例解決了原始代碼中存在的問題,並提供了更清晰的實現方式。記住要遵循最佳實踐,確保你的代碼安全、高效和易於維護。
以上是WooCommerce 自定義 WP_Query 獲取訂單詳情時出錯的解決方案的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undress AI Tool
免費脫衣圖片

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Stock Market GPT
人工智慧支援投資研究,做出更明智的決策

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

本教程詳細介紹瞭如何使用CSS精確隱藏HTML頁面中的特定文本內容,避免因不當選擇器導致整個父元素被隱藏的問題。通過為目標文本的包裹元素添加專屬CSS類,並利用display: none;屬性,開發者可以實現對頁面元素的精細化控制,確保只隱藏所需部分,從而優化頁面佈局和用戶體驗。

usemailto:inhreftCreateeMaillinks.startwithforbasiclinks,add? object = and&body = forpre-flycontent,andIncludeMultipleDresseSorcc =,bcc = foradvancedOptions。

本文探討了在HTML中調用外部JavaScript函數時常見的兩個問題:腳本加載時機不當導致DOM元素未就緒,以及函數命名可能與瀏覽器內置事件或關鍵字衝突。文章提供了詳細的解決方案,包括調整腳本引用位置和遵循良好的函數命名規範,以確保JavaScript代碼能夠正確執行。

UsethetitleattributeforsimpletooltipsorCSSforcustom-styledones.1.Addtitle="text"toanyelementfordefaulttooltips.2.Forstyledtooltips,wraptheelementinacontainer,use.tooltipand.tooltiptextclasseswithCSSpositioning,pseudo-elements,andvisibilityc

setThelangattributeInthehtmltagtagtagtospecifepageLanguage,例如forenglish; 2.使用“ es” es“ es” forspanishor“ fr” forfrench; 3. IncludereVariantswariantswariantswithCountryCountryCodeslike“ en-us” en-us“ en-us”或“ zh-cn”;

usecssfloatpropertytowraptextaroundanimage:floatleftfortextextontheright,floatrightfortextontheleft,addmarginforspacing,and clearFloatFloatStopReventLayOutissues。

本文探討了在包含跨域iframe的父div上捕獲mousedown事件的挑戰。核心問題在於瀏覽器安全策略(同源策略)阻止了對跨域iframe內容的直接DOM事件監聽。除非控制iframe源域名並配置CORS,否則無法實現此類事件捕獲。文章將詳細解釋這些安全機制及其對事件交互的限制,並提供可能的替代方案。

在使用Bootstrap進行網頁佈局時,開發者常遇到元素默認並排顯示而非垂直堆疊的問題,尤其當父容器應用了Flexbox佈局時。本文將深入探討這一常見佈局挑戰,並提供解決方案:通過調整Flex容器的flex-direction屬性為column,利用Bootstrap的flex-column工具類,實現H1標籤與表單等內容塊的正確垂直排列,確保頁面結構符合預期。
