WordPress get_post_type() doesn’t work when restoring a trashed post via undo

I have a custom post type that uses the following hook:

	array($this, 'custom_restore_function')

And the custom function looks as follows:

function custom_restore_function() {
	if(get_post_type() == 'custom_post_type') {

I have a very similar setup for custom_save_function, custom_trash_function, and custom_delete_function, and in all instances, get_post_type() works like a charm.

When you use the Trash action link to move a post to the trash, the link looks something like this:


And if you choose to restore that post from the trash screen via the Restore action link, it looks very similar:


The problem is that when you trash a post and then decide to restore it again via the Undo link in the confirmation message, the custom_restore_function will fail.

The Undo link looks something like this:


And as you can see, the format is a bit different.

After doing more research and taking a closer look inside post.php to see what get_post_type() is actually doing:

function get_post_type($the_post = false) {
	global $post;
	if(false === $the_post)
		$the_post = $post;
		$the_post = get_post($the_post);
		return $the_post->post_type;
	return false;

It appears that $post doesn’t contain the post when using the Undo action link. I would be interested in knowing why?

Nevertheless, the easiest way to solve this problem was to modify the if statement to check for the post_type query string, which fortunately is available inside the custom_restore_function:

function custom_restore_function() {
	if(get_post_type() == 'custom_post_type'
	|| $_GET['post_type'] == 'custom_post_type') {

Leave a Reply

Your email address will not be published.