Skip to content

Instantly share code, notes, and snippets.

@lucymtc
Last active March 3, 2021 13:40
Show Gist options
  • Select an option

  • Save lucymtc/4f0540d9758e46a07bc4dc250b952826 to your computer and use it in GitHub Desktop.

Select an option

Save lucymtc/4f0540d9758e46a07bc4dc250b952826 to your computer and use it in GitHub Desktop.
WordPress preview trashed posts
<?php
class Preview {
/**
* Register WordPress hooks and filters
*
* @return void
*/
public function register() {
add_filter( 'post_row_actions', [ $this, 'post_row_actions' ], 10, 2 );
if ( ! is_admin() ) {
add_filter( 'pre_get_posts', [ $this, 'show_trash_preview' ] );
}
}
/**
* Add a preview link for trashed posts.
*
* @param $actions
* @param $post
*
* @return mixed
*/
public function post_row_actions( $actions, $post ) {
if ( 'trash' === $post->post_status ) {
$actions['trash_preview'] = sprintf(
'<a target="_blank" href="%s">%s</a>',
esc_url( get_preview_post_link( $post ) ),
esc_html__( 'Preview', 'textdomain' )
);
}
return $actions;
}
/**
* Handle a trash preview.
*
* @param object $query The WP_Query object.
*
* @return object The WP_Query object, unchanged.
*/
public function show_trash_preview( $query ) {
if (
$query->is_main_query() &&
$query->is_preview() &&
$query->is_singular()
) {
add_filter( 'posts_results', [ $this, 'set_trash_to_draft' ], 10, 2 );
}
return $query;
}
/**
* Sets the post status to draft for preview.
*
* @param array $posts The post to preview.
*
* @return array Post being previewed.
*/
public function set_trash_to_draft( $posts ) {
remove_filter( 'posts_results', [ $this, 'set_trash_to_draft' ], 10, 2 );
if ( empty( $posts ) ) {
return $posts;
}
if ( 'trash' !== $posts[0]->post_status ) {
return $posts;
}
$posts[0]->post_status = 'draft';
return $posts;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment