問題描述

我正在一個插件中直接運行一些 WP 函數,其中包括 wp_insert_post(),如果出現問題,則返回一個 WP Error 對象,該錯誤的正確方法是什麼?使用內置的 WP 函數或 PHP 異常或 whatnot ..

最佳解決方案

  1. 將函數返回給變量。

  2. is_wp_error()檢查變量。

  3. 如果 true 相應處理,例如 trigger_error(),帶有 WP_Error->get_error_message()方法的消息。

  4. 如果 false – 照常進行。

用法:

function create_custom_post() {
  $postarr = array();
  $post = wp_insert_post($postarr);
  return $post;
}

$result = create_custom_post();

if ( is_wp_error($result) ){
   echo $result->get_error_message();
}

次佳解決方案

喜,

首先,您檢查天氣,您的結果是否為 WP_Error 對象:

$id = wp_insert_post(...);
if (is_wp_error($id)) {
    $errors = $id->get_error_messages();
    foreach ($errors as $error) {
        echo $error; //this is just an example and generally not a good idea, you should implement means of processing the errors further down the track and using WP's error/message hooks to display them
    }
}

這是通常的方式。

但是,WP_Error 對象可以在沒有發生任何錯誤的情況下進行實驗,只是作為一般的錯誤存儲,以防萬一。如果要這樣做,可以使用 get_error_code()檢查是否有錯誤:

function my_func() {
    $errors = new WP_Error();
    ... //we do some stuff
    if (....) $errors->add('1', 'My custom error'); //under some condition we store an error
    .... //we do some more stuff
    if (...) $errors->add('5', 'My other custom error'); //under some condition we store another error
    .... //and we do more stuff
    if ($errors->get_error_code()) return $errors; //the following code is vital, so before continuing we need to check if there's been errors...if so, return the error object
    .... // do vital stuff
    return $my_func_result; // return the real result
}

如果這樣做,那麼您可以像上面的 wp_insert_post()示例一樣檢查返回錯誤的進程。

班級是 documented on the Codex 。還有 a little article here

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。