2017-02-12 42 views
1

我正在使用WPCasa儀表板插件來允許用戶提交房地產對象。我必須使用外部服務來驗證對象。我想阻止WP更新數據庫,如果來自服務的響應有錯誤。停止wordpress提交如果無效。 (WPCasa)

我爲我的功能使用wpcasa自己的鉤子。


這是我的孩子主題functions.php部分:

function newListingAdded($ID, $post) { 

    ... 

    if ($post->post_date === $post->post_modified) { 
    // new post 
    $response = wp_remote_post($targetUrl.'listings/new', $options); 
    } else { 
    $response = wp_remote_post($targetUrl.'listings/update', $options); 
    } 

    $output = json_decode($response['body']); 
    if (is_array($output)) { 
    $_SESSION['messages'] = []; 
    foreach ($output as $error) { 
     if (isset($error->msg)) { 
     array_push($_SESSION['messages'], ['danger', $error->msg]); 
     } 
    } 
    } 
} 
add_action('publish_listing', 'newListingAdded', 10, 2); 

到目前爲止一切正常像預期。我只是無法弄清楚如何停止實際提交數據的WordPress。

回答

0

而不是使用從WPCasa的publish_listing行動(我找不到它的WPCasa文檔中,雖然),您可以改用來自WordPress的官方wp_insert_post_data過濾器。

現在,WP並未正式支持一種方法來阻止使用動作/掛鉤保存帖子,但是,如果您查看WP源代碼(參考:https://core.trac.wordpress.org/browser/tags/4.7/src/wp-includes/post.php#L3281),您會看到WP需要從wp_insert_post_data返回的$data值(要保存到數據庫的字段/值對的關聯數組),並將其傳遞給$ wpdb-> update()。

如果使用wp_insert_post_data如果$數據是返回一個布爾值false值,而不是由過濾器接收,然後它會阻止更新後的實際$data參數,如$ wpdb->更新()檢查有效的陣列,而不是假的,否則它不會對數據庫做任何事情(參考:https://core.trac.wordpress.org/browser/tags/4.7/src/wp-includes/wp-db.php#L2023

所以,你可以嘗試使用此代碼:

function newListingAdded($data, $postarr) { 
    if (!$data['ID']) { // If no post ID is set then it's a new post 
    $response = wp_remote_post($targetUrl.'listings/new', $options); 
    } else { 
    $response = wp_remote_post($targetUrl.'listings/update', $options); 
    } 

    $output = json_decode($response['body']); 

    if (is_array($output)) { 
    $_SESSION['messages'] = []; 

    foreach ($output as $error) { 
     if (isset($error->msg)) { 
     $_SESSION['messages'][] = ['danger', $error->msg]; // You can use the [] shorthand operator instead of the more verbose array_push() 
     $data = false; // If an error is found make $data false 
     } 
    } 
    } 

    return $data; 
} 

add_filter('wp_insert_post_data', 'newListingAdded', 10, 2); 

下面是此過濾器的參考: https://developer.wordpress.org/reference/hooks/wp_insert_post_data/