$conf, $runtime; function_exists('chdir') AND chdir(APP_PATH); $r = 'mysql' == $conf['cache']['type'] ? website_set('runtime', $runtime) : cache_set('runtime', $runtime); } function runtime_truncate() { global $conf; 'mysql' == $conf['cache']['type'] ? website_set('runtime', '') : cache_delete('runtime'); } register_shutdown_function('runtime_save'); ?>Bulk trashing post 'fails'|Programmer puzzle solving
最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

Bulk trashing post 'fails'

matteradmin11PV0评论

I want to bulk delete child posts of a custom post type, and I've made it work. I'm in class context:

// In a register method which registers all hooks.
add_action( 'wp_trash_post', [ $this, 'delete_child_posts' ], 10 );

public function delete_child_posts( int $post_id ) {
  $current_post = get_post( $post_id );

  // Check if current post is in the documentation post type.
  if ( $current_post->post_type !== 'documentation' ) {
    return;
  }

  // Only trigger when deleting parent post.
  if ( $current_post->post_parent !== 0 ) {
    return;
  }

  $child_pages = [
    'post_parent' => $post_id,
  ];

  $children = get_children( $child_pages );

  if ( empty( $children ) ) {
    return;
  }

  foreach ( $children as $child_post ) {
    wp_trash_post( $child_post->ID );
  }
}

This works super when I'm deleting parent post, or a single post (even a child).

But if I select the parent and the children posts, and try to delete them I'll get

Error in moving to Trash.

I go back and I see the posts, then refresh the browser, and they are in the trash.

So, what happens is: the parent post is deleted, the logic goes through, and child posts are trashed in the foreach loop. Then the first child goes in the hook callback since it's being trashed and this action will be triggered, I can see the post ID, and it doesn't pass the

// Only trigger when deleting parent post.
if ( $current_post->post_parent !== 0 ) {
  return;
}

check. So the action should exit and that's that. But I get an error. I tried returning post id, post object null, checking if the post status is trash, but I always get an error.

What am I missing?

Articles related to this article

Post a comment

comment list (0)

  1. No comments so far