我找到了解决方案。问题是“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