Celebrating 20 years online :)
Web Dev + WordPress + Security

X Theme Leftover Code Snippets

While working on the site’s 24th redesign, I ended up with about 10 code snippets that were awesome but ultimately not needed. So rather than just delete these tasty functions, I am posting them here for future reference. Who knows, during the next site update I may decide to implement or repurpose some of these techniques. And of course sharing is caring, so feel free to use any of these code snippets in your own projects. Check out the Table of Contents for an overview.

Table of Contents

HTML: Meta Tags

If you examine the source code of the current theme, you will notice that the viewport meta tag is omitted. Why? Because despite convention, the tag is not necessary in all cases. So after a bit of cross-browser testing, the design looked great on mobile devices without the meta viewport tag. And because absolute minimalism is my current thang, omitting meta viewport was a no-brainer. Here are a couple of common examples of this tag:

<meta name="viewport" content="initial-scale=1">
<meta name="viewport" content="width=device-width, initial-scale=1">

CSS: Multimedia Elements

I’ve been including these styles across designs for years now, but never really make use of them. So finally they were omitted from the new Perishable Press theme. If your site makes use of multimedia HTML elements audio, canvas, progress, or svg, these styles apply some basic styling to keep things looking good across browsers.

audio, canvas, progress { display: inline-block; vertical-align: baseline; }
audio:not([controls]) { display: none; height: 0; }
svg:not(:root) { overflow: hidden; }

CSS: Better Image Rendering

In previous designs, I did not hesitate to add as many vendor prefixes as needed to make things awesome. But not in the new design. Instead, I tried extra hard to avoid as many browser-specific properties as possible. For example, in my previous designs, I implemented CSS to improve or enhance image rendering using the image-rendering property. As far as I can tell it does work (kind of) in most cases for most images. But the amount of code required to cover all browsers is kinda nuts. So the following “better image rendering” styles were removed from my CSS palette.

img {
	-ms-interpolation-mode: nearest-neighbor;   /* IE 7+ */ 
	image-rendering: -webkit-optimize-contrast; /* Safari 6 */
	image-rendering: -webkit-crisp-edges;       /* Safari 7+ */
	image-rendering: -moz-crisp-edges;          /* Firefox 3.6+ */
	image-rendering: -o-crisp-edges;            /* Opera 12 */
	image-rendering: pixelated;                 /* Chrome 41+, Opera 26+ */

CSS: Breaking Long Words

Here are two CSS declarations that I used for previous designs. The first declaration “force-breaks” any long lines of text. For example, it’s a good idea to break long words and phrases inside of <table> elements. Otherwise they break out of their table cells, break layout, and decrease readability. The second declaration does the opposite: it tells browsers to not break or wrap long lines of text. For example, when displaying long lines of code inside of <pre> tags, we can display overflow via horizontal scroll instead of breaking or wrapping. Here is more information about wrapping long lines with CSS.

.text-wrap, table td {
     word-wrap:  break-word; 
 -ms-word-break: break-all;
     word-break: break-all;
     word-break: break-word;
-webkit-hyphens: auto;
   -moz-hyphens: auto;
        hyphens: auto;

.text-wrap-none, pre {
     word-wrap:  normal; 
 -ms-word-break: normal;
     word-break: normal;
     word-break: normal;
-webkit-hyphens: none;
   -moz-hyphens: none;
        hyphens: none;

JavaScript: Don’t Append Anchors

Something else I was toying with was disabling the appending of anchors to the URL displayed in the browser address bar. For example, if you click on a link pointing to #somewhere on the same page, the browser will update the address bar by appending the fragment identifier to the URL. So if you are visiting https://example.com/ and click on a link to #hashtag, the browser will display https://example.com/#hashtag. This code snippet disables that automatic updating of the URL when users click any internal #anchor links.

// don't append anchor to url
window.addEventListener('DOMContentLoaded', function(event) {
	var links = document.getElementsByTagName('a');
	for (var i = 0; i < links.length; i++) {
		if (!links[i].hash) continue;
		if (links[i].origin + links[i].pathname != self.location.href) continue;
		(function (anchorPoint) {
			links[i].addEventListener('click', function(e) {
			}, false);
		})(document.getElementById(links[i].hash.replace(/#/, '')));
}, false);

WP: Simple Art Directed Content

Art-directed content refers to content, scripts, and styles that are added to individual posts. For example, if you have a magazine-style site, and each post needs to be styled with a unique look and feel. Art-directed styles enable that to happen. I was using an outdated art-directed plugin, but in an effort to simplify my setup, I replaced the plugin with a simple yet effective function:

// simple art directed content
function shapeSpace_art_directed($content) {
	$id = get_the_ID();
	$art = get_post_meta($id, 'art_direction_single', true);
	if (!empty($art) && is_singular('post')) $content = $content . $art;
	return $content;
add_filter('the_content', 'shapeSpace_art_directed');

WP: Remove Empty Paragraphs

WordPress provides pretty solid formatting of markup in post content, but tends to go overboard with the wrapping of HTML comments with paragraph tags <p>. For example, when you have something <!-- like this --> in your post content, WordPress automatically will wrap it with <p> tags. This is frustrating because paragraph tags — even empty ones — usually are styled with some sort of margins or padding. So that means empty paragraphs can introduce unwanted vertical spacing in an otherwise immaculate design.

Making things worse, WordPress adds HTML comments for more tags (excerpts), so you’ve got at least one empty paragraph for each single post. Fortunately it’s possible to clean up any empty paragraphs with the following code snippet. Note that it’s also possible to take care of empty <p> tags using JavaScript or even a bit of CSS.

// remove empty paragraph tags
function shapeSpace_filter_post_content($content) {
	if (is_single()) $content = preg_replace('/<p>\s*<!--(.*)-->\s*<\/p>/i', '', $content);
	return $content;
add_filter('the_content', 'shapeSpace_filter_post_content');

WP: Set Cookies via Ajax

The new X theme used here at Perishable Press enables the user to switch themes, from the default “light” mode to the dark “night” mode. You can try it by clicking the round icon in the upper-right corner of the page. So if the user switches themes, their choice is remembered via small cookie. At first, I was using the WordPress Ajax API to set the cookie value, but later replaced it with a vanilla JavaScript technique.

// WordPress Ajax Cookies
function shapeSpace_ajax_switch_theme() {
	check_ajax_referer('ajax', 'nonce');
	if (isset($_POST['theme']) && ($_POST['theme'] === 'dark' || $_POST['theme'] === 'lite')) {
		$theme = ($_POST['theme'] === 'dark') ? 'dark' : 'lite';
		$expire = time() + (86400 * 30); // 86400 = 1 day
		$domain = 'perishablepress.com';
		// setcookie(name, value, expire, path, domain, secure, httponly)
		setcookie('xtheme', $theme, $expire, '/', $domain, true, true);
add_action('wp_ajax_switch', 'shapeSpace_ajax_switch_theme');
add_action('wp_ajax_nopriv_switch', 'shapeSpace_ajax_switch_theme');

WP: Add Item to Edit Post Rows

Another WordPress code snippet, this one adds a link item to each row on the “Edit Post” screen. The trick here is choosing the right filter hook, which for the Edit Post screen is post_row_actions. Likewise to filter rows on the “Edit Page” screen, we can use page_row_actions. In the following technique, we add a “View HTML” link to each row. Of course, you can tweak the code to add whatever markup/links you want :)

// Add Item to Edit Post Rows
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" title="View HTML of frontend page" href="view-source:', $html) : null;
	$actions = $html ? array_merge($actions, array('html' => $html)) : $actions;
	return $actions;
add_filter('post_row_actions', 'shapeSpace_modify_list_row_actions', 10, 2);
// add_filter('page_row_actions', 'shapeSpace_modify_list_row_actions', 10, 2);

Code Word

That’s all for this post. Thank you for the visit :)

About the Author
Jeff Starr = Web Developer. Security Specialist. WordPress Buff.
Wizard’s SQL for WordPress: Over 300+ recipes! Check the Demo »

3 responses to “X Theme Leftover Code Snippets”

  1. Jim S Smith 2018/09/02 7:07 pm

    Some good stuff, here!

    I generally still like to use “word-break”-ing properties for things like “pre”-tags, AND to take care of formatting problems with text when the page is viewed in “print-preview”.

    BTW: Tried a print-preview test of your current site’s theme: unfortunately, the code text in the boxed-content get cut off at the end of longer lines. I try to avoid formatting problems like this, because a few of my other blogs provide some educational content – that I like to make completely readable if the pages are printed out (especially to a “PDF”, as Linux natively supports). – Just my “two cents” on this little tidbit.


    CHEERS! :-)

    – Jim

    • Jeff Starr 2018/09/03 9:43 am

      Thanks for the feedback Jim! Gonna take a closer look at print styles and maybe add a conditional word-break property to muh pre tags. Cheers! :)

    • Jeff Starr 2018/09/05 2:01 pm

      Hey Jim, I ended up adding pre, pre code { word-break: break-word; white-space: pre-wrap; } to my print styles. I think it does the trick, let me know if anything looks weird. And thanks for the recommendation, much appreciated :)

Comments are closed for this post. Something to add? Let me know.
Perishable Press is operated by Jeff Starr, a professional web developer and book author with two decades of experience. Here you will find posts about web development, WordPress, security, and more »
BBQ Pro: The fastest firewall to protect your WordPress.
Crazy that we’re almost halfway thru 2024.
I live right next door to the absolute loudest car in town. And the owner loves to drive it.
8G Firewall now out of beta testing, ready for use on production sites.
It's all about that ad revenue baby.
Note to self: encrypting 500 GB of data on my iMac takes around 8 hours.
Getting back into things after a bit of a break. Currently 7° F outside. Chillz.
Get news, updates, deals & tips via email.
Email kept private. Easy unsubscribe anytime.