我找到了解決方案。問題是行動'delete_post'。 我把它改成基於郵政狀態轉變「trash_to_publish」:https://codex.wordpress.org/Post_Status_Transitions
現在一切工作正常。
/**
* Deletes all posts from author of company profile.
*/
function delete_all_posts_from_author($post_id) {
global $post;
$id = $post->ID;
// Only trigger if post type is "company"
if (get_post_type($id) == "company") {
$author_id = $post->post_author;
$posts_from_author = get_posts(
array(
'posts_per_page' => -1,
'post_status' => 'publish',
'post_type' => array('event','job'),
'author' => $author_id,
'fields' => 'ids', // Only get post ID's
)
);
foreach ($posts_from_author as $post_from_author) {
wp_trash_post($post_from_author, false); // Set to False if you want to send them to Trash.
}
}
}
add_action('publish_to_trash', 'delete_all_posts_from_author', 10, 1);
作爲獎勵,我可以使用的功能再度用戶發佈的所有帖子,如果我取消刪除公司簡介。
/**
* Untrash posts if company profile is untrashed
*/
function untrash_all_posts_from_author($post_id) {
global $post;
$id = $post->ID;
if (get_post_type($id) == "company") {
$author_id = $post->post_author;
$posts_from_author = get_posts(
array(
'posts_per_page' => -1,
'post_status' => 'trash',
'post_type' => array('event','job'),
'author' => $author_id,
'fields' => 'ids', // Only get post ID's
)
);
foreach ($posts_from_author as $post_from_author) {
wp_untrash_post($post_from_author); // Set to False if you want to send them to Trash.
}
}
}
add_action('trash_to_publish', 'untrash_all_posts_from_author', 10, 1);
希望有所幫助。如果我犯了一個錯誤,請讓我知道。
編輯:我已經改變了說法wp_delete_post()
到wp_trash_post()
因爲wp_delete_post()
僅適用於本地的帖子,頁面和附件。來自@rarst的大回答在這裏:https://wordpress.stackexchange.com/questions/281877/error-after-deleting-custom-post-type-with-a-function-no-trash-used/281888#281888
看起來不錯:)唯一的是wp_untrash_post()只有一個參數,但這是堅實的。 –
啊,謝謝你的提示。我會改變它:) – Cray
與@ DanielH.J相同。說 - 但對於'wp_trash_post()',@Cray。它只需要1個參數,即post_id。我認爲你對'wp_delete_post()'可能會感到困惑? –