Tag Archives: plugin

Jekyll For WordPress Developers

Jekyll is gaining popularity as a lightweight alternative to WordPress. It often gets pigeonholed as a tool developers use to build their personal blog. That’s just the tip of the iceberg — it’s capable of so much more!

Jekyll For WordPress Developers

In this article, we’ll take on the role of a web developer building a website for a fictional law firm. WordPress is an obvious choice for a website like this, but is it the only tool we should consider? Let’s look at a completely different way of building a website, using Jekyll.

The post Jekyll For WordPress Developers appeared first on Smashing Magazine.

Visit link:  

Jekyll For WordPress Developers

Enhancing Grid Design With GuideGuide, A Plugin For Photoshop And Illustrator

Almost five years ago, I had the honor of writing a post on Smashing Magazine about my Photoshop panel GuideGuide. Since then it has seen wild success as the most installed third-party Photoshop extension, an achievement I’m quite proud. In that time, I’ve added some powerful features and, most recently, expanded it to Illustrator. This post will give you a taste of how GuideGuide can change the way you use guides in Photoshop and Illustrator.

Enhancing Grid Design with GuideGuide, A Plugin For Photoshop And Illustrator

If you’re one of the many people who already use GuideGuide, please read on. You may discover some unconventional uses that are not immediately apparent. I’ll provide a overview of the major features, and then give some examples of advanced and unusual ways it can be used to make you a more efficient designer.

The post Enhancing Grid Design With GuideGuide, A Plugin For Photoshop And Illustrator appeared first on Smashing Magazine.

Credit:  

Enhancing Grid Design With GuideGuide, A Plugin For Photoshop And Illustrator

Eliminate Jargon on Your Landing Pages With Our Free Chrome Extension

What would you think if you wound up on this landing page?

jargon-filled-landing-page copy

Check out some of the terms being used:

“The Next Generation of Awesome”
“Bleeding edge solution”
“Age of disruption”
“World class features”

Might your BS detector start going off?

These words are superlatives — meaningless filler. The language is flowery (and not in a good way).

And while this is an extreme example, jargonistic, superlative-laden landing pages are everywhere.

They lack specificity and don’t drive home any message. They aren’t persuasive and their unique value proposition is a blur. They make people feel lost  — like they just crawled out of a fallout shelter for the first time in 35 years.

brendan-fraser-lost
Wait, where am I?

The worst part? You could have meaningless drivel on your landing page and not even know it.

No sweat. We created a Chrome extension that can help (props to Henneke Duistermaat who inspired this whole idea with her post 17 Words to Stop Using on Your Landing Pages).

Here’s how it works:

  1. Download and install Unbounce’s Dejargonator Chrome Extension
  2. Run it on any landing page or website — offending phrases will be highlighted in red. (You can test it on this extra sleazy page here.)
  3. Hover over the red text and see what’s wrong:
  4. dejargonator-screenshot-2

  5. Finally, update your page to be
    • Less sleazy and superlative-y
    • More specific (and thereby more persuasive)

Simple enough? Download the plugin below.

This article: 

Eliminate Jargon on Your Landing Pages With Our Free Chrome Extension

Three Approaches To Adding Configurable Fields To Your WordPress Plugin


Anyone who has created a WordPress plugin understands the need to create configurable fields to modify how the plugin works. There are countless uses for configurable options in a plugin, and nearly as many ways to implement said options. You see, WordPress allows plugin authors to create their own markup within their settings pages. As a side effect, settings pages can vary greatly between plugins.

In this article we are going to go over three common ways you can make your plugin configurable. We will start by creating a settings page and create our fields using the default WordPress Settings API. I will then walk you through how to set up your fields with a custom handler. Finally, I will show you how to integrate a great configurable fields plugin Advanced Custom Fields (ACF) into your own plugin.

The post Three Approaches To Adding Configurable Fields To Your WordPress Plugin appeared first on Smashing Magazine.

Originally from – 

Three Approaches To Adding Configurable Fields To Your WordPress Plugin

11 Ways to Accelerate Page Load Time Before Your Prospects Bounce

Science of Speed
This photo is called “Split second before motorcycle crash” — no joke. Image via Skitterphoto.

The creative is stellar.

Headline and value prop impactful. Hero image delightful.

But peeps ain’t converting.

Because the single biggest conversion killer is lurking behind the scenes, completely untouched.

Which is a shame, because speed (or lack thereof) often has a bigger impact on campaign conversions than any of that other stuff.

The impact of speed

Google experienced a 20% traffic drop years ago as a result of a 0.5 second delay — 0.5!

Think that’s bad? If an ecommerce page fails to load in under 3 seconds, it stands to lose nearly half its traffic. As a result, some of the savviest online brands now load in under a second. Less than one second!

The impact of speed only becomes exacerbated on mobile, where limited processing power and spotty connections are the norm. According to Kinsta’s excellent page speed guide74% of people on mobile would abandon if the page doesn’t load in 5 seconds.

Mobile data
Image via Kinsta.

And this is a world where mobile internet usage is fast outpacing desktop. Where a single conversion event isn’t limited to a single page.

The point? If pages aren’t loading, ain’t nobody converting.

Yes, your headline is important. The value prop needs to be clear. A beautiful page is nice to have. Social proof critical to adding credibility.

But if fast loading times aren’t happening, then landing page conversions aren’t either.

Here’s how to fix that.

(Please note that you’ll probably need some technical help to implement some of the following recommendations.)

Page speed TLDR

Accelerate your page load time with these 11 tips and tricks

Grab the 300-word summary of Brad Smith’s actionable post.
By submitting your email you’ll receive more Unbounce conversion marketing content, like ebooks and webinars.

1. Clean up your code

Tidy code doesn’t just make your developer happy, it makes pages load quicker, too.

Reducing the size of site files, especially front-end ones, can have a big impact. Even small issues like excess spaces, indentations, line breaks and superfluous tags can hurt your page load time.

JavaScript is fun. It allows you add little details, like that funny snake or tail that follows a user’s mouse pointer around the screen. Clever! (Sarcasm!) Often, though, JavaScript can be overkill on a landing page. Same with Ajax and other similar extravagances.

Instead, KISS. If you focus on simplicity, there’s (almost) no need for extra stuff.

But if you’re dead-set on keeping your precious scripts (read that in your best Gollum/Sméagol voice), at least load your above-the-fold content first, which is Google’s recommended method.

Gollum
Whoa, someone’s touchy about their scripts. Image via GIPHY.

Find out how your page’s JavaScript is loading with Varvy’s handy JavaScript Usage Tool, and then work on optimizing.

2. Minify HTML & CSS

Jumping on the reducing requests bandwagon, minifying HTML and CSS will help you to package and deliver page data in the most streamlined way possible.

Admittedly, we’re getting out of my comfort zone here. If you’re confident in your technical ability, check out this helpful article. Otherwise open up Google’s PageSpeed Insights, drop in your URL and then send the results to a trusted developer.

3. Utilize GZIP compression

GZIP compression deals with content encoding to again minimize server requests made by your browser. Ouch — that sentence made my brain hurt.

In non-technical terms, GZIP compression reduces your file sizes to enable faster load times. If a more detailed explanation piques your interest, here’s a helpful article.

Use GIDNetwork to see what the current compression on your site looks like now, as well as to get a few ideas of how it could be improved. (Insert helpful developer here.)

4. Minimize redirects

301 redirects are a standard SEO-friendly practice used to tell both search engines and visitors that a page has permanently moved to a new location. It’s a common best practice used when campaigns and sites evolve or change over time, and can help you cut down on broken links or 404 errors.

Computer error
404 errors make everyone angry. Image via Giphy.

Trouble is, too many redirects can also negatively impact speed. So the question is: How many? In typical fashion, Google’s answer is vague — they simply suggest minimizing or trying to eliminate them all together, because they cause extra network trips to verify data (which can be a killer on mobile devices especially).

Screaming Frog can help by quickly identifying all of the redirects currently on your site. In the example below, we found a little over 14% of Runnersworld.com pages contain a redirect. Ouch.

Screaming Frog
How do you get a frog to scream? Toad-al up your redirects.

The key is to dig deeper. What types of redirects are you seeing and why? What are they trying to accomplish? Looking at the example above, there seems to be a lot of temporary 302 redirects from social sharing platforms that can probably be cleaned up to avoid slowing page speed. Here’s a detailed guide from Varvy for more.

5. Relocate scripts

Believe it or not, even script placement can affect load times.

For example, if your tracking scripts are located above the fold or in the <head> of your landing page, your browser will have to download and deal with those scripts before getting to the stuff people actually come to see (like the page content).

It should also go without saying that having duplicate scripts (which is pretty common when multiple people are working on the same page) will slow things down a bit.

And do you really need five analytics packages on that landing page? Probably not. Like most things you’ve read so far, simplify and minimize to reduce the back-and-forth between browsers and servers.

6. Limit WordPress plugins

“Easy.” you say. “Obvious!” you exclaim.

If it’s really so easy, then open up WordPress right now and look at how many plugins your team has installed for simple things like social sharing or tracking. Things that can — and should — be done by a professional so you can completely avoid having to install these plugins in the first place.

The problem is: taking a bunch of third-party tools built by different people and shoehorning them into a Frankenstein-esque page is a recipe for disaster.

If you’d like to diagnose which plugins are worth keeping and which need to be deactivated immediately, you’re not going to like the answer… add another plugin!

P3 (or the Plugin Performance Profiler) will measure your site’s plugin performance and measure their impact on load times. At least you can rest assured knowing that this one will serve some utility while it’s installed.

7. Upgrade hosting

If you have plans to someday make money from your website (so probably everyone reading this blog), paying $3 per month for Godaddy hosting is not going to cut it.

One big reason is that many cheap hosting solutions are shared, meaning you’re sharing server space with many other sites (whose own performance might drag down yours).

That might also mean limited control over what you’re able to affect or change to improve things like site speed. This is especially true for ecommerce sites, which can experience sudden traffic jumps and contain many large media files. Simply put, hosting can make or break your campaign.

If you know what you’re doing, PCMag does a decent job ranking and rating dedicated web hosting services.

Best web hosting

If you’re less sure of what you’re doing or would simply like to not worry about it, a managed hosting option is preferable. This is especially true for WordPress websites — besides speed improvements you’re also getting extra security against external threats plus backups for internal mistakes. The aforementioned Kinsta, WP Engine and Pagely are some of the most popular choices.

8. Resize images

Death, taxes and people not resizing images before uploading them. These are universal truths you can always count on. Also, Mashable publishing terrible articles.

Tweet “Death, taxes & people not resizing images before uploading them. These are universal truths you can always count on.”

Asking browsers to automatically squeeze your original 1200px image down to 600px every time your landing page is loaded, multiplied across all visits for all pages and posts, creates a ton of unnecessary extra work. (Especially on mobile devices with limited processing power and relatively poor connectivity.)

Ideally, resize images before uploading them to the server. If that’s too much work (I ain’t judging, I’m lazy too), at least use WordPress’ built-in tool to resize images for you.

Image resizer

Taking this time-consuming, menial step helps you limit potential errors in mediocre browsers like Internet Explorer, because, well, everything causes errors in Internet Explorer (or whatever they’re calling it these days).

9. Compress images

After resizing your images, the next step should be to compress them to again reduce file size.

This is another often overlooked step, with an infographic from Radware claiming that 45%(!) of the top 100 ecommerce sites don’t compress images.

But optimizing your images can be a low-hanging-fruit approach to quickly speed up loading times, drastically reducing the amount of space — and work — they require.

There are a number of fast, free tools out there, like TinyJPG or Compressor.io, which can significantly reduce file size. The test seen below using Compressor.io resulted in a 73% reduction! Multiply that across all of your landing page images and we’re talking serious results.

Image compressor screenshot

10. Deliver Images with a CDN

See a pattern here yet?

Delivering images with a Content Delivery Network (or CDN) is like calling in reinforcements from servers located closer to your site’s visitors. That means it will try to use the closest ones first, using every trick in the book to cut down on the time and effort required to deliver content from server to a user’s browser.

Popular ones like CloudFlare and MaxCDN can drastically improve performance on highly visual sites.

Image CDN
Image via Cloudflare.

11. External Hosting

Another prudent option is to move large files, like images, audio or video, off of your servers entirely and use an external hosting platform like Imgur for images or Wistia for videos.

While we’ve beat the importance of image size to a metaphorical death already, bigger files like audio and video should almost always be hosted externally.

That’s critical, because rich media adoption is immense. It’s predicted that a whopping 74% of internet traffic in 2017 will be video.

Beyond the performance issues, external hosting providers also offer additional benefits like increased audience reach or features that increase interactions and conversions. Wistia founder Chris Savage lays out a few more reasons why external hosting is a good idea, if you’re interested.

Conclusion

74% of people would leave a site if it doesn’t load within 5 seconds. Which means that even if you’re leveraging all the best practices in the world to get those conversions, people won’t stick around long enough to actually see any of it.

Page speed improvements can range from the basic (upgrading your hosting and removing unnecessary plugins) to the more advanced (minifying files). But anything is certainly better than nothing. Even paying extra attention to how you’re uploading images can go a long way to improving performance.

Yes, implementing all of these changes will be a time-consuming process. No doubt. But it’s also the best way to give your landing pages a fighting chance to convert visitors.

Read this article – 

11 Ways to Accelerate Page Load Time Before Your Prospects Bounce

Advanced WordPress Management With WP-CLI


The command-line interface has always been popular in the world of developers, because it provides tools that boost productivity and speed up the development process. At first sight, it might seem hard to believe that using the command line to perform certain tasks is getting easier than using a graphical interface. The purpose of this article is to clear up your doubts about that, at least concerning WordPress tasks.

Advanced WordPress Management With WP-CLI

WordPress provides a graphical user interface for every administrative task, and this has helped to make it the most popular content management system on the web. But in terms of productivity, working with the command line enables you to accomplish many such tasks more efficiently and quickly.

The post Advanced WordPress Management With WP-CLI appeared first on Smashing Magazine.

This article:

Advanced WordPress Management With WP-CLI

Thumbnail

RICG Responsive Images For WordPress

I recently teamed up with Mat Marquis of the Responsive Images Community Group to help integrate responsive images into the WordPress platform. We decided to refactor a plugin that I had built several months ago, hoping that it would lead to a more useable and performant solution.

After months of pull requests, conversations on Slack and help from WordPress’ core team, we’re finally ready to share what we’ve been working on. You can download and install RICG Responsive Images1 from WordPress’ plugin directory, while keeping track of our development progress on GitHub2.

What Does The Plugin Do?

WordPress hasn’t changed the way it outputs the img tag in quite some time. And although there are plenty of ways to hook into WordPress’ native functions and alter the img snippet, doing so can be overwhelming for beginners and non-theme developers alike. Compound that with the complexity of Picturefill and of the srcset specification, and WordPress users have had few options for implementing a clean and properly functioning responsive images solution.

To solve this problem, we set out to build a plugin that gives users responsive images as soon as the plugin is installed, with no extra effort needed. No admin setting, media uploading configuration or coding is required. The plugin comes with one dependency3, a polyfill for browsers that don’t yet support native responsive images. Removing this file is completely optional and will not affect the functionality of the plugin, as long as the user has a modern browser.

As soon as an image is uploaded through the media interface, WordPress automatically creates three variations of the image at different sizes. When the plugin is activated, adding “Featured” and content images to a post will return WordPress’ standard image markup, with an added srcset attribute4. We’re using the srcset attribute because it’s the easiest attribute for both developers and users to add. While the picture element provides the user with a richer set of options5, we felt that the srcset attribute makes the most sense as an out-of-the-box solution. It’s also best to use when you’re focusing on resolution-switching more than art direction6 (more on that later in the article).

<a href="http://ricg.dev/wp-content/uploads/2015/01/image.jpg"><img class="alignnone size-full wp-image-6" src="http://ricg.dev/wp-content/uploads/2015/01/image.jpg" srcset="http://ricg.dev/wp-content/uploads/2015/01/image-150x150.jpg 150w, http://ricg.dev/wp-content/uploads/2015/01/image-300x300.jpg 300w, http://ricg.dev/wp-content/uploads/2015/01/image-1024x1024.jpg 1024w, http://ricg.dev/wp-content/uploads/2015/01/image.jpg 1800w" alt="a cool responsive image" width="1800" height="1800"></a>

The plugin is designed to be backwards-compatible, meaning that images added before the plugin was installed will be responsive when added to a post or “Featured Image” section. This is because it uses the image sizes previously defined by WordPress and the active theme’s functions.php file. The image ratio will be maintained throughout the srcset array, meaning that images differing from the aspect ratio of the initial uploaded image will be left out.

Theme developers can use the plugin to place responsive images wherever they’d like by using the tevkori_get_srcset_string() function, which takes an image’s ID and size as parameters.

<img src="myimg.png" <?php echo tevkori_get_srcset_string( 11, 'medium' ); ?> />

There’s also a tevkori_get_srcset_array() function that takes the same parameters and returns an array of srcset values for the specified image.

How Does The Plugin Work?

Most of the functionality happens when an image is dropped into WordPress’ WYSIWYG editor. Because all of the resized images will have been created during the uploading process, the only thing left to do is create an array containing the URLs of the available images in various sizes, as well as their dimensions. This array is then filtered to remove the image sizes with aspect ratios that don’t match the ratio of the full-sized image.

The array is created by calling the wp_get_attachment_image_src() function and storing the results. At the same time, we use wp_get_attachment_metadata() to retrieve the same results but for every possible variation of the image. Next, the ratio is calculated by multiplying each image’s width by the result of the initial image’s height divided by the initial image’s width. If that result matches the initial image’s height, then the image will be pushed into the final array, to be returned by the tevkori_get_srcset_array() function.

The tevkori_get_srcset_string() function calls tevkori_get_srcset_array() and places the result inside of the srcset attribute. A filter is applied to the image_send_to_editor function, where a regular expression is used to place the result of the tevkori_get_srcset_string() function directly after the src attribute in the image. The same process occurs for featured images, with a filter being applied to the post_thumbnail_html function.

If the image size is changed in the post’s editor, then the plugin will detect the change and update the srcset value accordingly. This ensures that the correct image ratio is always maintained. To enable this functionality, we’re using JavaScript to hook into the wp.media object7 and recalculating the srcset attribute by running the same image-ratio calculations defined in tevkori_get_srcset_array(). Before starting on this project, I was unaware of the wp.media object and its useful functionality. Because not much documentation for it exists, explaining in detail how we’re using it might be helpful. As it turns out, you can listen for an image-update event in the post’s editor by adding an event listener to the wp.media object.

wp.media.events.on( 'editor:image-update', function( args ) 
  var image = args.image;
  //more function logic
);

With this function, a theme developer can access every image as soon as it has been updated in the post’s editor. You can also take advantage of Underscore8, which is used as a dependency by the media uploader to edit image data on the fly. In the case of our plugin, we’re using a helpful Underscore utility to get our image-size ratios once the editor:image-update event has been fired.

// Grab all of the sizes that match our target ratio and add them to our srcset array.
_.each(sizes, function(size)
  var softHeight = Math.round( size.width * metadata.height / metadata.width );

  // If the height is within 1 integer of the expected height, let it pass.
  if ( size.height >= softHeight - 1 && size.height <= softHeight + 1  ) 
    srcsetGroup.push(size.url + ' ' + size.width + 'w');
  
});

To learn more about how we hook into the wp.media object, be sure to look at the code in wp-tevko-responsive-images.js9.

The sizes Attribute

Currently, this plugin doesn’t add a sizes attribute10 to complement the srcset attribute. The reason is that we initially recognized that we could never predict what those sizes would need to be, because they depend on how the user’s theme is styled. While we are working on a solution to this issue, we’re encouraging all users to include a sizes attribute on their own, either manually or via another WordPress plugin, such as wp-lazysizes11. One thing to note is that the responsive images specification has recently changed, and use of the w descriptor must now be followed by a sizes attribute. Omitting the sizes attribute will render the markup technically invalid, while still falling back to a default size of 100vh.

What About Features X, Y And Z?

While much more can be done with responsive images, you’ve probably noticed a few use cases that this plugin doesn’t cover. The first thing that we’re usually asked about is a feature for art direction. Art direction refers to loading differently styled images at different breakpoints — whether that means entirely new images or the same image cropped or focused differently. This feature would require use of the picture element, which in turn would mean a lot more markup to generate the final image.

Adding this feature to WordPress would be impossible without the addition of a fairly complicated interface in WordPress’ media uploader, because the user would need to be able to define all breakpoints and then select images to be loaded in when those breakpoints are reached. Our goal for this plugin is to allow for a basic implementation of responsive images, with absolutely no configuration needed by the user. So, we’ve decided to omit this feature. We will, however, do our best to allow art direction to work side by side with our plugin as we expand the API for theme developers.

Lazy-loading and image compression are two other features that we have no plans to implement, simply because they fall beyond the scope of a more or less “default” solution for responsive images. Again, we aim to make the addition of these features possible for theme developers who use our plugin via a feature-rich API.

What’s Next?

While the plugin is available for everyone to download and install, we’re actively working to make it better. So, users can expect frequent updates, resolved issues and an all-around better functioning plugin as time goes on. We’re planning to add more features, such as the sizes attribute and hooks that allow theme developers to further customize the plugin.

Another feature we have yet to consider is ratio descriptors like 2x and 3x for “Retina” use cases. Better documentation and support are coming soon as well. Eventually, we’d like to see this plugin become a part of WordPress’ core, which means that it will stay minimalist, admin-less and easy to use.

(il, al, ml)

Footnotes

  1. 1 https://wordpress.org/plugins/ricg-responsive-images/
  2. 2 https://github.com/ResponsiveImagesCG/wp-tevko-responsive-images
  3. 3 http://scottjehl.github.io/picturefill/
  4. 4 http://www.smashingmagazine.com/2013/08/21/webkit-implements-srcset-and-why-its-a-good-thing/
  5. 5 http://alistapart.com/article/responsive-images-in-practice#section4
  6. 6 http://css-tricks.com/responsive-images-youre-just-changing-resolutions-use-srcset/
  7. 7 http://codex.wordpress.org/Javascript_Reference/wp.media
  8. 8 http://underscorejs.org/
  9. 9 https://github.com/ResponsiveImagesCG/wp-tevko-responsive-images/blob/master/js/wp-tevko-responsive-images.js
  10. 10 http://ericportis.com/posts/2014/srcset-sizes/#part-2
  11. 11 https://github.com/aFarkas/wp-lazysizes

The post RICG Responsive Images For WordPress appeared first on Smashing Magazine.

Read article here:  

RICG Responsive Images For WordPress

Thumbnail

Encrypting Blacklisted Words In WordPress With ROT13

Countless algorithms for encrypting data exist in computer science. One of the lesser known and less common encryptions is ROT13, a derivative of the Caesar cypher1 encryption technique.

In this tutorial, we’ll learn about ROT13 encryption and how it works. We’ll see how text (or strings) can be programmatically encoded in ROT13 using PHP. Finally, we’ll code a WordPress plugin that scans a post for blacklisted words and replaces any in ROT13 encryption.

If you own a blog on which multiple authors or certain group of people have the privilege of publishing posts, then a plugin that encrypts or totally removes inappropriate words might come in handy

Introduction

ROT13 (short for “rotate by 13 places,” sometimes abbreviated as ROT-13) is a simple encryption technique for English that replaces each letter with the one 13 places forward or back along the alphabet. So, A becomes N, B becomes O and so on up to M, which becomes Z. Then, the sequence continues at the beginning of the alphabet: N becomes A, O becomes B and so on up to Z, which becomes M.

A major advantage of ROT13 over other rot(N) techniques (where “N” is an integer that denotes the number of places down the alphabet in a Caesar cypher encryption) is that it is “self-inverse,” meaning that the same algorithm is applied to encrypt and decrypt data.

Below is a ROT13 table for easy reference.

| A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z |
--------------------------------------------------------------------------------------------------------  
| N | O | P | Q | R | S | T | U | V | W | X | Y | Z | A | B | C | D | E | F | G | H | I | J | K | L | M |

If we encrypted the domain smashingmagazine.com in ROT13, the result would be fznfuvatzntnmvar.pbz, and the sentence “Why did the chicken cross the road?” would become “Jul qvq gur puvpxra pebff gur ebnq?”

Note that only letters in the alphabet are affected by ROT13. Numbers, symbols, white space and all other characters are left unchanged.

Transforming Strings To ROT13 In PHP

PHP includes a function, str_rot13(), for converting a string to its ROT13-encoded value. To encode text in ROT13 using this function, pass the text as an argument to the function.

<?php

echo str_rot13('smashingmagazine.com'); // fznfuvatzntnmvar.pbz

echo str_rot13('The best web design and development blog'); // Gur orfg jro qrfvta naq qrirybczrag oybt

Using ROT13 In WordPress

Armed with this knowledge, I thought of ways it might be handy in WordPress. I ended up creating a plugin that encodes blacklisted words found in posts using ROT13.

The plugin consists of a textearea field (located in the plugin’s settings page) in which you input blacklisted words, which are then saved to the database for later reuse in WordPress posts.

Without further fussing, let’s start coding the plugin.

Setting Up the Plugin

First, include the plugin’s file header2.

<?php

/*
Plugin Name: Rot13 Words Blacklist
Plugin URI: http://smashingmagazine.com/
Description: A simple plugin that detects and encrypts blacklisted words in ROT13
Version: 1.0
Author: Agbonghama Collins
Author URI: http://w3guy.com
Text Domain: rot13
Domain Path: /lang/
License: GPL2
*/

As mentioned, the plugin will have a settings page with a textarea field that collects and saves blacklisted words to WordPress’ database (specifically the options table).

Below is a screenshot of what the plugin’s settings (or admin) page will look like.

Settings page of the plugin.3
(See large version4)

Now that we know what the options page will look like, let’s build it using WordPress’ Settings API5

Building the Settings Page

First, we create a submenu item in the main “Settings” menu by using add_options_page(), with its parent function hooked to admin_menu action.

add_action( 'admin_menu', 'rot13_plugin_menu' );

/**
 * Add submenu to main Settings menu
 */
function rot13_plugin_menu() 
	add_options_page(
		__( 'Rot13 Blacklisted Words', 'rot13' ),
		__( 'Rot13 Blacklisted Words', 'rot13' ),
		'manage_options',
		'rot13-words-blacklist',
		'rot13_plugin_settings_page'
	);

The fifth parameter of add_options_page() is the function’s name (rot13_plugin_settings_page), which is called to output the contents of the page.

Below is the code for rot13_plugin_settings_page().

/**
 * Output the contents of the settings page.
 */
function rot13_plugin_settings_page() 
	echo '<div class="wrap">';
	echo '<h2>', __( 'Rot13 Blacklisted Words', 'rot13' ), '</h2>';
	echo '<form action="options.php" method="post">';
	do_settings_sections( 'rot13-words-blacklist' );
	settings_fields( 'rot13_settings_group' );
	submit_button();

Next, we add a new section to the “Settings” page with add_settings_section(). The textarea field we mentioned earlier will be added to this section with add_settings_field(). Finally, the settings are registered with register_setting().

Below is the code for add_settings_section(), add_settings_field() and register_setting().

	// Add the section
	add_settings_section(
		'rot13_setting_section',
		'',
		'rot13_setting_section_callback_function',
		'rot13-words-blacklist'
	);


	// Add the textarea field to the section.
	add_settings_field(
		'blacklisted_words',
		__( 'Blacklisted words', 'rot13' ),
		'rot13_setting_callback_function',
		'rot13-words-blacklist',
		'rot13_setting_section'
	);

	// Register our setting so that $_POST handling is done for us
	register_setting( 'rot13_settings_group', 'rot13_plugin_option', 'sanitize_text_field' );

The three functions above must be enclosed in a function and hooked to the admin_init action, like so:

/**
 * Hook the Settings API to 'admin_init' action
 */
function rot13_settings_api_init() 
	// Add the section
	add_settings_section(
		'rot13_setting_section',
		'',
		'rot13_setting_section_callback_function',
		'rot13-words-blacklist'
	);


	// Add the textarea field to the section
	add_settings_field(
		'blacklisted_words',
		__( 'Blacklisted words', 'rot13' ),
		'rot13_setting_callback_function',
		'rot13-words-blacklist',
		'rot13_setting_section'
	);

	// Register our setting so that $_POST handling is done for us
	register_setting( 'rot13_settings_group', 'rot13_plugin_option', 'sanitize_text_field' );


add_action( 'admin_init', 'rot13_settings_api_init' );

Lest I forget, here is the code for the rot13_setting_callback_function() and rot13_setting_section_callback_function() functions, which will output the textarea field and the description of the field (at the top of the section), respectively.

/**
 * Add a description of the field to the top of the section
 */
function rot13_setting_section_callback_function() 
	echo '<p>' . __( 'Enter a list of words to blacklist, separated by commas (,)', 'rot13' ) . '</p>';


/**
 * Callback function to output the textarea form field
 */
function rot13_setting_callback_function() 
	echo '<textarea rows="10" cols="60" name="rot13_plugin_option" class="code">' . esc_textarea( get_option( 'rot13_plugin_option' ) ) . '</textarea>';

At this point, we are done building the settings page for the plugin.

Up next is getting the plugin to detect blacklisted words and encrypt them with ROT13.

Detecting Blacklisted Words and Encrypting in ROT13

Here is an overview of how we will detect blacklisted words in a WordPress post:

  • A post’s contents are broken down into individual words and saved to an array ($post_words).
  • The blacklisted words that were saved by the plugin to the database are retrieved. They, too, are broken down into individual words and saved to an array ($blacklisted_words).
  • We iterate over the $post_words arrays and check for any word that is on the blacklist.
  • If a blacklisted word is found, then str_rot13() encodes it in ROT13.

It’s time to create the PHP function (rot13_filter_post_content()) that filters the contents of a post and then actually detects blacklisted words and encrypts them in ROT13.

Below is the code for the post’s filter.

/**
 * Encrypt every blacklisted word in ROT13
 *
 * @param $content string post content to filter
 *
 * @return string
 */
function rot13_filter_post_content( $content ) 

	// Get the words marked as blacklisted by the plugin
	$blacklisted_words = esc_textarea( get_option( 'rot13_plugin_option' ) );

    // If no blacklisted word are defined, return the post's content.
	if ( empty( $blacklisted_words ) ) 
		return $content;
	

	else 

		// Ensure we are dealing with "posts", not "pages" or any other content type.
		if ( is_singular( 'post' ) ) 

			// Confine each word in a post to an array
			$post_words = preg_split( "/b/", $content );

			// Break down the post's contents into individual words
			$blacklisted_words = explode( ',', $blacklisted_words );

			// Remove any leading or trailing white space
			$blacklisted_words = array_map(
				function ( $arg ) 
					return trim( $arg );
				,

				$blacklisted_words
			);


			// Iterate over the array of words in the post
			foreach ( $post_words as $key => $value ) 

				// Iterate over the array of blacklisted words
				foreach ( $blacklisted_words as $words ) 

					// Compare the words, being case-insensitive
					if ( strcasecmp( $post_words[ $key ], $words ) == 0 ) 

						// Encrypt any blacklisted word
						$post_words[ $key ] = '<del>' . str_rot13( $value ) . '</del>';
					
				}
			}

			// Convert the individual words in the post back into a string or text
			$content = implode( '', $post_words );
		}

		return $content;
	}
}


add_filter( 'the_content', 'rot13_filter_post_content' );

While the code above for the filter function is quite easy to understand, especially because it is so heavily commented, I’ll explain a bit more anyway.

The is_singular( 'post' ) conditional tag ensures that we are dealing with a post, and not a page or any other content type.

With preg_split(), we are breaking down the post’s contents into individual words and saving them as an array by searching for the RegEx pattern b, which matches word boundaries6.

The list of blacklisted words is retrieved from the database using get_option(), with rot13_plugin_option as the option’s name.

From the screenshot of the plugin’s settings page above and the description of the textarea field, we can see that the blacklisted words are separated by commas, our delimiter. The explode PHP function breaks down the blacklisted words into an array by searching for those commas.

A closure7 is applied to the $blacklisted_words array via array_map() that will trim leading and trailing white spaces from the array values (the individual blacklisted words).

The foreach construct iterates over the post’s words and check whether any word is in the array of blacklisted words. Any blacklisted word that gets detected is encrypted in ROT13 and enclosed in a <del> tag.

The $post_words array is converted back to a string or text and subsequently returned.

Finally, the function is hooked to the the_content filter action.

Below is a screenshot of a post with the words “love” and “forever” blacklisted.

A post with the blacklisted word love encoded in ROT138

Wrapping Up

ROT13 is a simple encryption technique that can be easily decrypted. Thus, you should never use it for serious data encryption.

Even if you don’t end up using the plugin, the concepts you’ve learned in creating it can be applied to many situations, such as obfuscating or encrypting inappropriate words (such as profanities) in ROT13, which would be a nice feature in a forum where people have the freedom to post anything.

Hopefully, you have learned a thing or two from this tutorial. If you have any question or a contribution, please let us know in the comments.

(dp, al, il)

Front page image credit: Wikipedia9.

Footnotes

  1. 1 http://en.wikipedia.org/wiki/Caesar_cipher
  2. 2 http://codex.wordpress.org/File_Header
  3. 3 http://www.smashingmagazine.com/wp-content/uploads/2014/12/rot13-plugin-settings-page-large-opt.jpg
  4. 4 http://www.smashingmagazine.com/wp-content/uploads/2014/12/rot13-plugin-settings-page-large-opt.jpg
  5. 5 http://codex.wordpress.org/Settings_API
  6. 6 http://www.regular-expressions.info/wordboundaries.html
  7. 7 php.net/manual/en/functions.anonymous.php
  8. 8 http://www.smashingmagazine.com/wp-content/uploads/2014/11/post-with-blacklisted-word-opt.jpg
  9. 9 http://en.wikipedia.org/wiki/Caesar_cipher

The post Encrypting Blacklisted Words In WordPress With ROT13 appeared first on Smashing Magazine.

Continue reading here:  

Encrypting Blacklisted Words In WordPress With ROT13