Skip to content

Remove posts or pages from menu when trashed (or set to draft)

Ever wanted posts to be removed from a menu when deleted? Maybe. Ever wanted them removed when set to draft? Less likely but I’ll tell you how to do both anyway!

The first is really easy and I pulled the solution from an open ticket on WordPress Trac.

add_action( 'wp_trash_post', '_wp_delete_post_menu_item' );

and that’s it. that line can go into a plugin or your functions.php file (plugin is more appropriate). It’s hooking into the action of putting a post in the trash (which carries with it the post ID) and calling the function to remove any corresponding menu items from any custom menu. easy.

If you’d like to have published posts (even custom post types) that get set back to draft taken out of the menu, you can use a function like this:

function pype_remove_draft_from_menu($post) {
   _wp_delete_post_menu_item($post->ID);
}
add_action( 'publish_to_draft', 'pype_remove_draft_from_menu');

also easy! This uses one of the post transition hooks, which takes the form of $oldstatus_to_$newstatus So if you wanted to catch posts moving from draft into published you would name the hook draft_to_publish

Related, a useful post status to use is the “auto-draft” which is the status given when you click “add new” and haven’t saved anything yet. This can be used to set up default content or settings for a post. In the past I’ve used it to set comments off by default for a particular post type. I might as well show you how:

function pype_default_comments_off( $data, $postarr ) {
   if( $data['post_type'] == 'post' && $data['post_status'] == 'auto-draft' ) {
      $data['comment_status'] = 'closed';
   }
   return $data;
}
add_filter( 'wp_insert_post_data', 'pype_default_comments_off', 99, 2 );

Add Your Comment (Get a Gravatar)

Get a Gravatar! Your Name

Your email address will not be published. Required fields are marked *.

*