2017-04-14 33 views
0

我在自定義的WooCommerce網站中創建了一個函數。這在前端運行良好,但wp-admin中斷。 Wp-admin顯示一個http-500錯誤。wordpress函數中斷wp-admin

這是函數:

// Set currency based on visitor country 

function geo_client_currency($client_currency) { 
     $country = WC()->customer->get_shipping_country(); 
      switch ($country) { 
      case 'GB': return 'GBP'; break; 
      default: return 'EUR'; break; 
     } 

} 
add_filter('wcml_client_currency','geo_client_currency'); 

我已經設置了WP-調試的真實,它會拋出這樣的消息:

Fatal error: Uncaught Error: Call to a member function get_shipping_country() on null in 

所以它必須做一些事情:$國家= WC() - > customer-> get_shipping_country();但我找不到它。 也許有人可以幫助我。

謝謝先進。

+1

'WC()'不返回任何東西,它有一個'customer'屬性。 – Sirko

+0

這是有道理的。但是如何編輯這個函數,使它在前端和後端都能工作? – quinox

+0

因爲它是一個PHP函數,所以你會遇到問題讓它在前端工作。 WC()函數實際返回什麼? – Sirko

回答

0

customer屬性未在後端設置爲WC_Customer的實例,因此您無法調用get_shipping_country()方法。

檢查customer在使用前不爲空(默認)。

function geo_client_currency($client_currency) { 
    if (WC()->customer) { 
     $country = WC()->customer->get_shipping_country(); 

     /** 
     * Assuming more are going to be added otherwise a switch is overkill. 
     * Short example: $client_currency = ('GB' === $country) ? 'GBP' : 'EUR'; 
     */ 
     switch ($country) { 
      case 'GB': 
       $client_currency = 'GBP'; 
       break; 

      default: 
       $client_currency = 'EUR'; 
     } 
    } 

    return $client_currency; 
} 
add_filter('wcml_client_currency', 'geo_client_currency'); 
+0

謝謝Nathan。解決了問題! – quinox