A fresh mix of code snippets and tutorials

WordPress: Add “View HTML” Button on Edit Post Screen

On a recent project, I found myself viewing the HTML source for every post and page on a WordPress-powered site. After about a thousand clicks, I decided to write a code snippet that adds a “View HTML” button (it’s actually just a link) for each post row displayed on the WordPress “Edit Post” screen. So when you are on the Edit Post screen and hover over a post row, you can click on the”View HTML” link, which will be located next to the existing default links, “Edit”, “Quick Edit”, “Trash”, and “Preview”.

Add “View HTML” Button

Here is the magic snippet that saved me probably hours of time (the site had a LOT of posts). Instead of taking two or three clicks to view the source code of each post, the following code will add a button to do it in one click.

// Add "View HTML" button for each row on Edit Post screen
function shapeSpace_modify_list_row_actions($actions, $post) {
	// check for CPT and capability if needed, use nonce if needed
	$html = isset($actions['view']) ? $actions['view'] : null;
	$html = $html ? str_replace('View', 'HTML', $html)  : null;
	$html = $html ? str_replace('href="', 'target="_blank" rel="noopener noreferrer" title="View HTML of frontend page" href="view-source:', $html) : null;
	$actions = $html ? array_merge($actions, array('html' => $html)) : $actions;
	return $actions;
add_filter('page_row_actions', 'shapeSpace_modify_list_row_actions', 10, 2);
add_filter('post_row_actions', 'shapeSpace_modify_list_row_actions', 10, 2);

This code may be added to WordPress via your theme’s functions.php file or custom plugin. No changes are required, simply save changes and done. As written, this code adds the button to both WP Posts and Pages. You can comment out either of the last two add_filter lines to limit button display to one or the other.

Note: This technique uses safe blank target best practices, as explained in my Perishable Press article, WordPress and the Blank Target Vulnerability.

Learn more

Digging Into WordPressWordPress Themes In DepthWizard’s SQL Recipes for WordPress