當使用者登入時,您可能想要顯示他購買的產品列表,例如在自定義的 “我的帳戶” 標籤中。

客戶端需要這個,所以我決定把它編碼為一個短碼。請享用!

PHP 程式碼段:顯示使用者購買的所有產品 – WooCommerce

  /**   * @snippet       Display All Products Purchased by User - WooCommerce     * @sourcecode    https://businessbloomer.com/?p=22004   * @author        Rodolfo Melogli   * @compatible    Woo 3.0.4   */    add_shortcode( 'my_products', 'bbloomer_user_products_bought' );    function bbloomer_user_products_bought() {  global $product, $woocommerce, $woocommerce_loop;  $columns = 3;  $current_user = wp_get_current_user();  $args = array(      'post_type'             => 'product',      'post_status'           => 'publish',      'meta_query'            => array(          array(              'key'           => '_visibility',              'value'         => array('catalog', 'visible'),              'compare'       => 'IN'          )      )  );  $loop = new WP_Query($args);    ob_start();    woocommerce_product_loop_start();    while ( $loop->have_posts() ) : $loop->the_post();  $theid = get_the_ID();  if ( wc_customer_bought_product( $current_user->user_email, $current_user->ID, $theid ) ) {  wc_get_template_part( 'content', 'product' );   }   endwhile;     woocommerce_product_loop_end();    woocommerce_reset_loop();  wp_reset_postdata();    return '<div class="woocommerce columns-' . $columns . '">' . ob_get_clean() . '</div>';  }    

然後使用您需要的短程式碼(僅當使用者登入時才會工作,例如 “我的帳戶” 頁面將是理想的):

  [my_products]    


可以在哪裡新增此程式碼?

您可以將 PHP 程式碼片段放置在主題或子主題的 functions.php 檔案的底部(如果是 CSS 程式碼,請新增到主題的 style.css 檔案底部),修改之前建議先備份原始檔案,若出現錯誤請先刪除此程式碼。


這段程式碼是否正常可用?

或者是您有更好的解決方案想要分享?請到薇曉朵 WooCommerce 中文論壇留言告知,我們希望可以幫到更多國內的 WooCommerce 使用者也希望您的參與。


需要關於 WooCommerce 的幫助?

請觀看我們提供的免費影片教程或到薇曉朵 WooCommerce 中文論壇提問,會有專業技術團隊提供相關幫助。