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:

1
2
3
4
add_action(
    'untrash_post',
    array($this, 'custom_restore_function')
);
add_action(
	'untrash_post',
	array($this, 'custom_restore_function')
);

And the custom function looks as follows:

1
2
3
4
5
function custom_restore_function() {
    if(get_post_type() == 'custom_post_type') {
        $this->set_custom_post_type_display_status(1);
    }
}
function custom_restore_function() {
	if(get_post_type() == 'custom_post_type') {
		$this->set_custom_post_type_display_status(1);
	}
}

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:

post.php?post=118&action=trash&_wpnonce=910f2d7f30

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

post.php?post=118&action=untrash&_wpnonce=ddb4c9c68b

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:

edit.php?post_type=custom_post_type&doaction=undo&action=untrash&
ids=118&_wpnonce=ea0d2a97d2

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:

1
2
3
4
5
6
7
8
9
10
function get_post_type($the_post = false) {
    global $post;
    if(false === $the_post)
        $the_post = $post;
    elseif(is_numeric($the_post))
        $the_post = get_post($the_post);
    if(is_object($the_post))
        return $the_post->post_type;
    return false;
}
function get_post_type($the_post = false) {
	global $post;
	if(false === $the_post)
		$the_post = $post;
	elseif(is_numeric($the_post))
		$the_post = get_post($the_post);
	if(is_object($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:

1
2
3
4
5
6
function custom_restore_function() {
    if(get_post_type() == 'custom_post_type'
    || $_GET['post_type'] == 'custom_post_type') {
        $this->set_custom_post_type_display_status(1);
    }
}
function custom_restore_function() {
	if(get_post_type() == 'custom_post_type'
	|| $_GET['post_type'] == 'custom_post_type') {
		$this->set_custom_post_type_display_status(1);
	}
}

Leave a Reply

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