Making your WordPress Database HEART Healthy

Making your WordPress Database HEART Healthy

If your WordPress site was analogous to the human body, the core code would be the brain and your plugins and theme would be the rest of the central nervous system that makes the site do what you tell it to do.  However, in the Information Age, where data is currency and the lifeblood of your site and business, the WordPress database would be the heart of your site. The queries you execute on your database would be the arteries and veins that feed that lifeblood to your site and receive data from your audience.

This is why it is so important to maintain the database as part of your regular site maintenance workflow.  Today I will be sharing with you a 5 step plan (or workflow) to use in maintaining your site and keeping it HEART healthy.  So let’s get right to the HEART of the matter.

1. Have a backup

The first rule of database maintenance is NOT “We don’t talk about database maintenance.”  In fact, it is critical that you maintain your database with the same care that you should maintain your own heart. The first rule of database maintenance is very simple – ALWAYS make a backup before you do any work on a production site. In fact, Rule 1a can best be described as “Inasmuch as it is possible, NEVER work on the database in a production or live environment.”

Managed WordPress hosts provide a staging environment specifically designed for maintenance and development. I recommend that you always make a backup copy of your site’s database before doing any work on it. Additionally, work in an isolated environment from your production/live site environment so that, in the event that something goes wrong, your live site is not impacted. If your hosting provider does not provide staging environments, you can always copy your site into a separate installation of WordPress on your server or into a localized MAMP (Mac) or WAMP (Windows) virtual machine host.

2. Eliminate the clutter

In the same way that you would reduce your cholesterol and blood sugar to healthy levels in order to allow your blood to flow freely, you want to eliminate data in your website that is stale, obsolete, or unnecessary.  The most common content that slows down website performance is orphaned metadata found in the postmeta, commentmeta, and usermeta tables. This metadata is often left behind when improperly removing old posts, comments, and users from the site’s database.  Leftover information becomes more data for queries run on these tables to parse through, slowing down the effort to return the needle in the haystack.

There are also a variety of popular plugins that will help with this cleanup process like WP Sweep and Advanced Database Cleaner.  Other items that you also want to watch out for include:

  • Outdated revisions
  • Trash/Spam comments
  • Trash Posts
  • Orphaned term relationships
  • Expired transients (The current WordPress core version now automatically deletes these.)

Another consideration with e-commerce sites is to archive obsolete products and outdated order histories, provided your business model will allow for this as part of your workflow.  WooCommerce does have tools available for archiving older products and orders based on customizable parameters.

3. Analyze the configuration

When you are feeling chest pains, one of the first things a cardiologist will do is take pictures or perform an ECG/EKG to get an idea of how and why your heart is causing you pain. In the same way, you want to analyze how your database is configured in order to make sure that data is flowing correctly and efficiently to protect the integrity of your database.

One thing you want to make sure of is to check for the default WordPress indexes and review any custom indexes you have created. Indexes are designed to work like filters for your data to speed up the WHERE and ORDER BY clauses of your MySQL queries. However, a word of caution is warranted here. Complex indexes that are made on frequently updated fields (using INSERT and UPDATE queries) can make those queries run slower.  Executing a “mysqlcheck” command with the “–check” flag will identify any corrupted tables or indexing errors.

Additionally, one thing to keep in mind is that there are two different types of storage engines in MySQL – MyISAM and InnoDB. The important things to know about these are how they use memory and how they exercise locking during queries. From a high-level point of view, MyISAM utilizes physical disk space for memory when processing read/write query functions.  InnoDB, on the other hand, utilizes a dedicated slice of RAM memory for processing your query functions, making InnoDB much more efficient. Additionally, MyISAM locks the entire table when querying, whereas InnoDB only locks the current row being scanned during a query.  InnoDB also has an automatic repair feature. As MyISAM is 20-year-old technology and will soon be no longer supported in newer MySQL versions, it is recommended to uniformly use InnoDB for all tables in your database.

4. Reclaim empty space

In the same way blood clots can slow your blood flow, thus making your heart have to work harder, empty space in your database can lead to database fragmentation requiring optimization to reclaim that dead space. Simply put, deleting content from your database does not automatically reclaim that disk space on the server where the database is stored. In fact, the content that was there is actually replaced with a whitespace of sorts. As a result, you will often notice after deleting large amounts of data from a website that the directory size of your server-configured mysql directories differs from the actual amount of data within the database (seen through MySQL CLI, phpMyAdmin, or third-party database connection tools).

In order to reclaim this space, there are two methods you can use. From the server command line, you can execute a “mysqlcheck” command with the “–auto-repair” flag.  Otherwise, you can use phpMyAdmin to execute an Optimize Tables function. However, I must advise a word of warning regarding this function. As this is a destructive process of literally rebuilding your database tables, if you are performing this action in a live environment you will want to do this during an off-peak time frame.  For example, if you have a large wp_options table, when optimizing this table, your site will go offline until the table rebuild is complete. This is one of the many reasons why I strongly advise against doing this kind of maintenance in a production environment.

5. Transfer to production

Now comes the time for surgical precision. Just as with a heart transplant you are replacing a worn out heart with a new, healthier organ, this last step is all about bringing your hard work from the four previous steps to fruition. If your workflow allowed you to safely perform the previous tasks in production, then you can skip this step.

If your hosting provider has the tools available, you can use a one step deployment method to copy your newly repaired site/ database to the live/production environment.  However, there is a caveat. With e-commerce sites, you will need to ensure your deploy does not overwrite any new orders placed during the maintenance timeframe.  With WooCommerce sites, order data is stored in four tables:

      • wp_posts
      • wp_postmeta
      • wp_woocommerce_order_items
      • wp_woocommerce_order_itemmeta

You could ignore these tables in your deploy by selectively choosing which tables to migrate. Alternatively, WooCommerce provides tools to help you safely backup the new orders and then merge them into your repaired site.  You could also utilize the native WordPress Exporter to export the live site and then reimport it to merge the orders after the deploy of the repaired database.

In Conclusion

Just as your doctor will check your heart when you go in for your regular checkups, it is imperative that you perform regular maintenance on your website database.  Regular for your workflow is subjective and really depends on the flow of data in and out of your site. Some sites may require maintenance once a month, some twice a year, others once a week.  It all depends on your individual situation. Trim the fat and reduce the clutter. If necessary to perform “surgery,” hire a specialist like a qualified database administrator. You don’t want your family practitioner performing open heart surgery; that’s the job of a cardiac surgeon. Make it a regular exercise to maintain your database and fine tune your configurations to help your site continue to perform at top shape:

  • Have a backup
  • Eliminate the clutter
  • Analyze the configuration
  • Reclaim empty space
  • Transfer to production

Take H.E.A.R.T.

David Noland serves as a senior technical support administrator and in-house WordPress Database Subject Matter Expert for WP Engine, LLC in Austin, TX.  He fancies himself a world history junkie and he has nearly halfway completed his bucket list item of stepping foot on all 7 continents, having traveled from North America to Asia and Europe.  He is married to Sara, his wife of 20 years, and has 4 adult children and 7 grandchildren.

The post Making your WordPress Database HEART Healthy appeared first on Torque.

Read Full Article Here

Code Review Part 3 – Building & Refactoring the Posts Generator

Code Review Part 3 – Building & Refactoring the Posts Generator

In the last article, I walked you through a code review and refactoring process for the FilterWPQuery class in Josh Pollock’s plugin.  We made his class more readable and performant. But we did not cover the posts generator code in the getPosts() method; rather, I left that review for this article. Why? There are two reasons.

First, I wanted to give us time to thoroughly review this section of code. There are several areas that we can improve. This code provides a learning opportunity to improve your own code as we dive into code style, PHP namespace importing, string processing, and more.

Second, the design of this class and specifically this method can be made flexible for real-world applications. Josh notes that this plugin is for educational purposes. Let’s use this opportunity to explore polymorphism and how to convert this code into a handler for flexible implementations.

In this article, you and I will do a thorough code review of the posts generation code.  Then in Part 4 of this series, we’ll dive into making this class more flexible.

To refresh your memory, this is the starting posts generator code:

<?php
namespace CalderaLearnRestSearch;
/**
 * Class FilterWPQuery
 *
 * Changes WP_Query object during REST API requests
 *
 * @package CalderaLearnRestSearch
 */
class FilterWPQuery implements FiltersPreWPQuery
{
  // Code left out for brevity.
  
  	/** @inheritdoc */
	public static function getPosts() : array
	{
		//Create 4 mock posts with different titles
		$mockPosts = [];
		for ($i = 0; $i <= 3; $i++) {
			$post = new WP_Post((new stdClass()));
			$post->post_title = "Mock Post $i";
			$post->filter = 'raw';
			$mockPosts[$i] = $post;
		}
		//Return a mock array of mock posts
		return $mockPosts;
	}
}

Posts Generation is Just One Implementation

When you read the above code, notice the inline comment.  Why does it exist? Think about it.

It’s there because the code is actually generating posts, albeit mocked posts. It’s a generator, i.e. it builds posts and returns them back. It’s just one implementation that is possible when filtering posts for a search request.

Josh designed the getPosts() method as an arbitrary example of generating mock posts as a learning exercise. I get that.  But as a learning exercise, we can focus our attention on the intent of this method and begin to think about a real-world application.

I want you to think about the more broad scope of handling a search request.

When filtering the posts for a search request, you will likely need to do some processing such as fetching, sorting, assembling, and/or even generating. This “processing” depends upon your project’s needs and business rules, as well as the specific search request itself. That means we need different implementations to handle each of these request scenarios in order to send back the relevant posts for the search request.

We’ll dive into the concept of designing for different implementations in the next article. But here, let’s generally agree that when filtering a search request, we need the flexibility to handle different business rules in our project.

Do you agree? If no, let’s talk about it. If yes, then we accept that the getPosts() method should be able to handle different needs for filtering posts.

The code that is within this method is just one implementation, i.e. one way of handling the posts filtering. Your real-world application will need different implementations, possibly multiple scenarios in the same project.

Therefore, the task of generating posts needs its own implementation.  In our current design, that means abstracting it to a separate method.  In doing so, here’s what happens:

  1. We eliminate the inline comment as the method’s name tells us what it’s doing.
  2. We set up the getPosts() method to be flexible.

Let’s refactor.

Abstract the Posts Generator

Let’s create a new private method called generatePosts().  The name of this method tells us that it will generate posts.

Since we are creating a new method, a better strategy is to tell it how many posts you want it to build for you.

/** @inheritdoc */
public static function getPosts() : array
{
	return static::generatePosts(4);
}

/**
 * Generates an array of mocked posts.
 *
 * @param int $quantity Number of posts to generate.
 *
 * @return array
 */
private static function generatePosts($quantity) : array
{
	$mockPosts = [];
	for ($i = 0; $i < $quantity; $i++) {
		$post = new WP_Post((new stdClass()));
		$post->post_title = "Mock Post $i";
		$post->filter = 'raw';
		$mockPosts[$i] = $post;
	}

	return $mockPosts;
}

Import Classes Into Current Namespace

PHP gives us the ability to import classes and functions that are in a different namespace.  While we could use the full namespace in our code, it makes the code less readable. Even when the class is in the global namespace, the backslash is distracting when we read the code, as it adds another character. They clutter up the code.

A better approach is to import each into the current namespace using the keyword use.  By doing this, we can use the class anywhere in our namespace without the preceding backslash.

<?php
namespace CalderaLearnRestSearch;

use stdClass;
use WP_Post;

// Code left out for brevity

      $post = new WP_Post((new stdClass()));

Make the Loop’s Indexer Tell Us What It Represents

We all know that $i represents the current value of a loop’s index. It’s a common naming convention. However, when that variable is used in the code, it’s a better practice to give it an expressive, descriptive name to tell you what value it represents within its given context.

When you read $i in the generator code, what does it mean to you?  Is the value the number of the loop?

No, here in this context, it represents the post’s number.  Yes, it is an indexer, but since we are including it as part of the post’s title, it tells us the post’s number.

Then let’s call it $postNumber:

for ($postNumber = 0; $i < $quantity; $postNumber++) {
  $post = new WP_Post((new stdClass()));
  $post->post_title = "Mock Post $postNumber";
  $post->filter = 'raw';
  $mockPosts[$postNumber] = $post;
}

Array Index is Unnecessary & Less Performant

In this line of code, the specifying telling PHP to create the post at this index position is unnecessary:

$mockPosts[$postNumber] = $post;

Why?

What position (key) does an indexed array start at when adding elements into the array?  Zero. Indexed arrays start at position 0.

Look at the code.  What is the starting post number, $postNumber, in the loop?  Zero.

Then as the loop iterates, what happens to the $postNumber?  It increments up by one.

How about an indexed array? What happens each time you add another element into the array like this $array[] = $someValue;? Internally, PHP increments to the next index to add the element.

Do you get where I’m going with this?  The loop indexes the variable and PHP indexes the array.  The array’s index matches the loop’s index.

Let me help you visualize what’s going on:

  1. First Loop:  The loop starts and $postNumber is 0.  The code creates a new post.  It’s assigned it to element 0 in the array.
  2. Next Loop:  The loop increments $postNumber to 1.  The code creates a new post.  It’s assigned it to element 1 in the array.
  3. Repeat until done.

It’s unnecessary to tell it to put the post into a specific index point within the array. Why? PHP does it automatically for us.

Therefore, we can refactor the code like this:

$mockPosts[] = $post;

Why is this a better strategy?

First, it’s less code to read.  That means we don’t have to try and figure out if the indexed array could be out of sync with the loop.

Second, it’s faster. Why?  PHP does not have to look up the value bound to that variable before adding the new post element.  It’s one less step to be processed.

Tell PHP Where Embedded Code Starts and Ends in a String

PHP needs your help to quickly identify the variable or code that is embedded inside of a string. How do you do this? By wrapping the variable (or code) inside of curly braces.

The opening curly brace tells the PHP parser: “Hey, this is the start of an embedded variable.”  PHP keeps reading until it gets to the closing curly brace. Using the curly braces, you are declaring that this is an embedded variable that needs to be processed to get the value to insert into the string.

Why?

Imagine that the title had another character after the variable. How would PHP know that the variable is $postNumber and not that plus the other character(s)?

The parser is greedy.  Strings are comprised of different alphanumeric characters.  How does PHP know where a variable or code starts and ends? We can help it out by using the curly braces to explicitly tell it our intent.

There’s an additional benefit.  When you and I read this string, the wrapped code jumps out at us.  It catches our attention, alerting us that this needs to be processed.

$post->post_title = "Mock Post {$postNumber}";

Code Tip: Standardize using this technique.  It will keep your code consistent and eliminate the need to figure out if you should wrap it or not.  Just wrap it.

Code Style and Formatting Matter

Code style is an important component of quality and readability.

”Code formatting is important….The functionality that you create today has a good chance of changing in the next release, but the readability of your code will have a profound effect on all the changes that will ever be made….Your style and discipline survive, even though your code does not.”

Robert C. Martin, Clean Code: A Handbook of Agile Software Craftsmanship

In our standards, we define how our code should be named, constructed, and formatted.  Many of the editors and IDEs we use can be configured to let us automatically reformat an entire file to our defined standard.

There are multiple items that need clean up in our new method.  Let’s walk through them together.

Remove Unnecessary Parentheses From Post Instantiation

Right now, the code has a double set of parenthesis around the creation of a new standard object.  We only need one set.

I’d also suggest adding spacing within the parentheses to give more emphasis to the new object.

$post = new WP_Post( new stdClass() );

Align Grouped Assignments

Aligning a group of assignments allows us to quickly recognize that these are assignments.  It draws our attention to the equals sign, where we can separate the work from the variable. It makes code more readable by communicating: “Hey, these are all assignment operations.”

Let’s Review

Here is our refactored method to generate posts:

private static function generatePosts($quantity): array
{
	$mockPosts = [];
	for ($postNumber = 0; $postNumber < $quantity; $postNumber++) {
		$post             = new WP_Post( new stdClass() );
		$post->post_title = "Mock Post {$postNumber}";
		$post->filter     = 'raw';
		$mockPosts[]      = $post;
	}

	return $mockPosts;
}

I covered a lot in this article.  Let’s summarize what we did and identify how it improves the code’s readability and/or performance:

The improvement Readability Performance
Created a new private method for the posts generator code
Imported the classes into the current namespace
Renamed the loop’s indexer variable
Removed the array indexer
Wrapped the embedded variable within the string
Improved the code style and formatting

The final code and each refactoring step is documented in the Pull Request on GitHub.  I invite you to explore it.

Let’s Discuss It

What do you think? Do each of these improvements make sense to you?  No, really, I want to hear what you think.

From the step-by-step walkthrough, do you see how to implement each of these strategies in your own code?

I look forward to discussing this review and refactor process with you.  Feel free to ask me any questions and share your opinions in the comments below.

With over 3 decades of high-tech, enterprise engineering experience, Tonya is on a mission to develop professional WordPress developers and engineers at Know the Code, unlocking each person’s potential and empowering each to excel, innovate, and prosper.

The post Code Review Part 3 – Building & Refactoring the Posts Generator appeared first on Torque.



Read Full Article Here

Code Review Part 2: Improving Readability and Performance of the FilterWPQuery Class

Code Review Part 2: Improving Readability and Performance of the FilterWPQuery Class

In the last article, I walked you through the problem of letting “no go” conditions flow through your code. I showed you how to refactor the code to solve the problem and make the code more readable.  In this article, you and I will continue doing a code review and refactoring of the FilterWPQuery in Josh Pollock’s plugin.

In Part 3 of Advanced OOP for WordPress, Josh walks you through how he refactored the FilterWPQuery class to make it more testable. Let’s use his latest version of the class for our code review process.

<?php
namespace CalderaLearnRestSearch;
/**
 * Class FilterWPQuery
 *
 * Changes WP_Query object during REST API requests
 *
 * @package CalderaLearnRestSearch
 */
class FilterWPQuery implements FiltersPreWPQuery
{
	/**
	 * Priority for filter
	 *
	 * @var int
	 */
	protected static $filterPriority = 10;
	/**
	 * Demonstrates how to use a different way to set the posts that WP_Query returns
	 *
	 * @uses "posts_pre_query"
	 *
	 * @param $postsOrNull
	 * @return WP_Post[]
	 */
	public static function callback($postsOrNull)
	{
		//Only run during WordPress API requests
		if (static::shouldFilter()) {
			//Prevent recursions
			//Don't run if posts are already sent
			if (is_null($postsOrNull)) {
				//Get mock data
				$postsOrNull = static::getPosts();
			}
		}
		//Always return something, even if its unchanged
		return $postsOrNull;
	}
	/** @inheritdoc */
	public static function shouldFilter() :bool
	{
		return did_action('rest_api_init');
	}
	/** @inheritdoc */
	public static function addFilter() : bool
	{
		return add_filter('posts_pre_query', [FilterWPQuery::class, 'callback'], 10);
	}
	/** @inheritdoc */
	public static function removeFilter() : bool
	{
		return remove_filter('posts_pre_query', [FilterWPQuery::class, 'callback'], 10);
	}
	/** @inheritdoc */
	public static function getFilterPriority() : int
	{
		return static::$filterPriority;
	}
	/** @inheritdoc */
	public static function getPosts() : array
	{
		//Create 4 mock posts with different titles
		$mockPosts = [];
		for ($i = 0; $i <= 3; $i++) {
			$post = new WP_Post((new stdClass()));
			$post->post_title = "Mock Post $i";
			$post->filter = 'raw';
			$mockPosts[$i] = $post;
		}
		//Return a mock array of mock posts
		return $mockPosts;
	}
}

To get us started, I’ll quickly refactor the opening conditionals by applying the same “return early” strategy that you and I did in the last article:

public static function callback($postsOrNull)
{
	// Bail out if not a WordPress REST Request.
	if ( ! static::shouldFilter()) {
		return $postsOrNull;
	}
	
	// Bail out if posts were already sent.
	if ( ! is_null($postsOrNull)) {
		return $postsOrNull;
	}

	// Get mock data
	$postsOrNull = static::getPosts();

	return $postsOrNull;
}

Now we can start our code review.

Make shouldFilter Decide If We Should Filter or Not

Notice that Josh created a new method called shouldFilter().  This method’s name tells us that it decides whether the callback should filter the pre-query or not.

When reviewing the callback’s code, that decision should be based on two conditions:

  1. WordPress is currently processing a RESTful request.
  2. The incoming value is null, meaning we need to go get the posts.

There’s a problem. In the current design, the shouldFilter() method is not deciding whether to filter or not. Rather, it’s only doing one of the checks.

How can we fix this problem?  We can move the null checker into the method.

Let’s walk through it together step-by-step.

Step 1: Move the Null Checker

The first step is to relocate the null checker from the callback() method and put it into the shouldFilter() method.  That’s easy enough to cut it from one method and paste it into another.

But hold on, the null checker is dependent upon the given input.  That means we declare $postsOrNull as a method’s parameter.

public static function shouldFilter($postsOrNull) :bool
{
	// REST request checker.
	if ( ! did_action('rest_api_init')) {
		return false;
	}

	// Null checker.
	if ( ! is_null($postsOrNull)) {
		return false;
	}

	return true;
}

Step 2: Flip the Checker Order to Improve Performance

Let me ask you a question.  What happens if the method receives null?  Look at the code. What happens?

Yes, it returns false back and does its job.  But look at the control flow. First, it has to go through the REST request checker.

Think about the order of the checkers.  Should we do the REST request check before checking what we received?

The answer to that question depends upon the complexity of the code.  In this case, it is more performant (faster) to flip the order and do the null checker first.

Why?  Look at the code.  The PHP function is_null is very quick, whereas the the WordPress function did_action() has more code that needs to be processed.

Flipping the order allows us to do the faster check first.  Then if it fails, the code will more quickly bail out and return early.

public static function shouldFilter($postsOrNull) :bool
{
	// Null checker.
	if ( ! is_null($postsOrNull)) {
		return false;
	}

	// REST request checker.
	if ( ! did_action('rest_api_init')) {
		return false;
	}

	return true;
}

Step 3: Abstract the REST Checker to Improve Readability

Right now the REST checker requires an inline comment for us to quickly understand its intent (i.e. what it’s doing).  Let’s remove that comment and I’ll ask you a question.

if (did_action('rest_api_init')) {}

Can you quickly understand what the intent of this check? No. I can’t.  Do you agree? Then we need to refactor this code to make it tell us.

I want to stop right here for a moment and share a code tip with you. Code should be expressive and highly human readable. It should tell us what’s happening so that we can quickly get our work done.

When code needs a comment, that’s typically a clue.  The way you know if it needs to be refactored is by reading the code without the comment and then asking yourself: “Can I quickly understand what’s going on?”  If you answer no, then refactor.

”Clean code is simple and direct. Clean code reads like well-written prose. Clean code never obscures the designer’s intent but rather is full of crisp abstractions and straightforward lines of control.”

Grady Booch, Clean Code: A Handbook of Agile Software Craftsmanship

Let’s refactor this checker by creating a private method:

public static function shouldFilter($postsOrNull) :bool
{
	if ( ! is_null($postsOrNull)) {
		return false;
	}

	if ( ! static::doingREST()) {
		return false;
	}

	return true;
}

/**
 * Checks if WordPress is doing a REST request.
 *
 * @return bool
 */
private static function doingREST() : bool
{
	return did_action('rest_api_init');
}

Notice that the method’s name describes the behavior of this checker.  We no longer need the inline comments. When you come back to this code next week or next year, the code will convey its message to you more quickly.

Remember, readability is a major cornerstone of quality code. Make it tell. Make it human readable.

Step 4: Just Return the Conditional’s Decision

I often see this code pattern:

if ( ! static::doingREST()) {
  return false;
}

return true;

Why do we need to explicitly return true or false? Think about it.

The conditional is already returning its decision in a boolean format. That means the decision has been made. Why not simply return its decision?

return static::doingREST();

Why is this strategy better?

  1. It’s less code to read and maintain.
  2. It’s more performant (faster) because there is only one line of code for PHP to process.

Here is our refactored code to this point:

public static function callback($postsOrNull)
{
	if ( ! static::shouldFilter($postsOrNull)) {
		return $postsOrNull;
	}

	// Get mock data
	$postsOrNull = static::getPosts();

	return $postsOrNull;
}

public static function shouldFilter($postsOrNull) :bool
{
	if ( ! is_null($postsOrNull)) {
		return false;
	}

	return static::doingREST();
}

/**
 * Checks if WordPress is doing a REST request.
 *
 * @return bool
 */
private static function doingREST() : bool
{
	return did_action('rest_api_init');
}

Step 5: Update the Interface

The last step is to update the method in the interface to declare the incoming input:

/**
 * Checks if the request should be filtered or not.
 *
 * @param array|null $postsOrNull Array of WP_Posts or null.
 * @return bool
 */
public static function shouldFilter($postsOrNull) :bool;

Now the interface and implementation match.

Skip the Assignment and Just Return

Let’s look at these couple lines of code:

// Get mock data
$postsOrNull = static::getPosts();

return $postsOrNull;

What do you notice?  Think about what these lines of code are doing.

The returned array of posts from the getPosts() method is being assigned to a variable first before being returned to the filter event.  Why? It’s not used anywhere.

This code is an example of an unnecessary assignment.  Here, we can just return whatever is returned from

<code>getPosts()</code>

public static function callback($postsOrNull)
{
	if ( ! static::shouldFilter($postsOrNull)) {
		return $postsOrNull;
	}

	return static::getPosts();
}

This refactor is better because:

  1. It’s less code to read and maintain.
  2. It’s more performant (faster) because:
    1. PHP does not have to create the variable in its symbols table.
    2. It does not have to bind that variable to the array’s memory location.
    3. It avoids a variable lookup before returning.
    4. There is only one line of code for PHP to process.

You can learn more about how PHP manages its memory by reading the PHP Internals Book.

Callback is Too Generic. Make it Tell Us What It Does.

I noted early how important it is to make code tell us what’s going on. That starts with how we name our functions and methods.  These are our workers. They do stuff. Therefore, they should start with a verb and then be descriptive and expressive about its behavior.

The name “callback” is generic.  That word means that the method is bound to something that will invoke it.  But it doesn’t tell us anything about what will happen.

What does this method do?

  1. It’s a filter, which changes the given input for the ’posts_pre_query’ event.
  2. It gets or generates an array of posts to be used by the query.

Therefore, in essence, it’s a filter that changes the pre-query.  Let’s rename it to filterPreQuery.  What do you think?

In making this name change, we’ll have to change it in the interface and each of the tests that Josh built. That’s easy enough with a global search and replace.

Use the Priority Level Property

Take a look at the addFilter() and removeFilter() methods.  Notice that the priority level is hard-coded. Why?  Stick with me as I explain the thought process.

The class has a property that holds the value of the priority level.  There’s a method to get that property.

Imagine that you wanted to change it from 10 to say 99.  In order to make that change, how many places in the class do you have to remember to change? 3.

What happens if you forget to replace one of them?  A bug might occur.

Using the DRY principle, we strive to eliminate redundant code.  One of the reasons is to eliminate the problem I just explained.

How do we fix this one?  We can use the property when adding or removing the filter hook:

/** @inheritdoc */
public static function addFilter() : bool
{
	return add_filter('posts_pre_query', [FilterWPQuery::class, 'filterPreQuery'], static::$filterPriority);
}

/** @inheritdoc */
public static function removeFilter() : bool
{
	return remove_filter('posts_pre_query', [FilterWPQuery::class, 'filterPreQuery'], static::$filterPriority);
}

Let’s Review

I covered a lot in this article.  Together, you and I walked through the code review process to improve the FilterWPQuery class.  Though this class is small, there were quite a few code quality improvements.

Let’s look at what we did to improve readability and performance:

The improvement Readability Performance
Made the shouldFilter method decide whether the class should filter or not.
Flipped the order of the checkers.
Created a new private method to tell us the intent of checking if WordPress is processing a RESTful request.
Returned the decision of the conditional.
Skipped the variable assignment to simply return the array from getPosts().
Gave the callback method a more expressive name to tell us what it does. We made that name start with a verb, as method’s do work.
Made the shouldFilter method decide whether the class should filter or not.

In addition, we made the code more maintainable:

  1. Used the priority level’s property to replace the hard-coded integers in the add and remove methods.

All of these improvements are designed to increase the class’ code quality.

What’s Next?

How about the posts generator code in the getPosts() method? I think we’ve done enough in this article. Don’t you? Let’s continue the code review and improvement process in Part 3.

The final code and each refactoring step is documented in the Pull Request on GitHub.  I invite you to explore it.

Let’s Discuss It

What do you think?  Do each of these improvements make sense to you?  No, really, I want to hear what you think.

From the step-by-step walkthrough, do you see how to implement each of these strategies in your own code?

I look forward to discussing this review and refactor process with you.  Feel free to ask me any questions and share your opinions in the comments below.

With over 3 decades of high-tech, enterprise engineering experience, Tonya is on a mission to develop professional WordPress developers and engineers at Know the Code, unlocking each person’s potential and empowering each to excel, innovate, and prosper.

The post Code Review Part 2: Improving Readability and Performance of the FilterWPQuery Class appeared first on Torque.



Read Full Article Here

Code Review Part 1: Fixing Design Flaw with the “Return Early” Strategy

Code Review Part 1:  Fixing Design Flaw with the “Return Early” Strategy

While reading Josh Pollock’s first article in his Advanced OOP for WordPress series, I noticed opportunities to improve his code’s quality and performance.  So I reached out to him. As a fellow educator, he suggested that I do a code review and then publish my insights in a series of articles here on Torque as a companion to his series.

In this Code Quality Review series, I will present one or more code quality opportunities and provide details and insights to help you improve your code.

Let’s start with the posts_pre_query method in his FilterWPQuery class:

<?php
class FilterWPQuery
{
	public static function posts_pre_query( $postsOrNull, $query ) {
		//Only run during WordPress API requests
		if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
			//Prevent recursions
			remove_filter( 'posts_pre_query', [ FilterWPQuery::class, 'posts_pre_query' ], 10 );
			//Don't run if posts are already sent
			if ( is_null( $postsOrNull ) ) {
				//Create 4 mock posts with different titles
				$mockPosts = [];
				for ( $i = 0; $i <= 3; $i ++ ) {
					$mockPosts[ $i ]             = ( new WP_Post( ( new stdClass() ) ) );
					$mockPosts[ $i ]->post_title = "Mock Post $i";
					$mockPosts[ $i ]->filter     = "raw";
				}
				//Return a mock array of mock posts
				return $mockPosts;
			}
			//Always return something, even if its unchanged
			return $postsOrNull;
		}
	}
}

When you look at the structure of this method, what do you notice? Focus on the indentation. Notice that there are multiple nested conditionals. Where is the business logic, i.e. the main intent of this method?  It is wrapped inside of these conditionals.

This design is a bad coding practice and a flawed design.

Let’s explore why in the rest of the article.  Then you and I will refactor his code together, step-by-step. Finally, I’ll give you an implementation strategy to identify and refactor these patterns in your code.

Exploring the Design Flaw

To illustrate my points, I will borrow the phrase “go/no go” from manufacturing days to describe the result of a conditional.  A “go” state means the check passes and the process can continue. A “no go” state means the check fails and the process should stop.

Refer back to Josh’s code above and look specifically at the conditionals. When a conditional passes, that is a “go” as it is saying: “If this conditional passes my check, then run the code inside of my control block.”

How about when it fails, meaning that it finds a “no go?” Look at the code. What happens? The business logic does not run because the conditional is guarding it.  That’s the behavior we want. But how about the “no go?” It continues running all the way to the end of the method. That is a design flaw. Why?

The conditional identifies a “no go” condition.  This “no go” is a stopping point, meaning that when you find one, you don’t want any of the code below it to run.

This flowchart will help you to visualize the paths through the code:

Notice that a “no go” skips over the normal control flow (i.e. the business logic), bypassing it, and flowing the end of the method. In other words, the “no go” continues processing, whereas the normal control flow does not. That is the design flaw.

Wait, isn’t that the opposite of what we want?  When we find a “no go,” we don’t want it to continue processing and flowing; rather, we want it to stop the method’s processing.

The effect of this flawed design is the “no go” exit point shifts from where the conditional finds it to the end of the method.

A Better Strategy – Return Early on a “No Go”

A better design is to stop the method’s execution and “return early” at the point where the code finds a “no go”.  Refer to this flowchart:

Implementing this design clearly communicates your intent to stop, thereby, reducing the shifts in control flow and immediately improving your code’s quality.

This strategy is not new, in fact, Kent Beck first presented the idea of guard clauses in 1997 in his book, Smalltalk Best Practice Patterns.

The Approach is the Problem

Let’s start with understanding the problem.  The problem is the approach.

When designing a function, you may think about the conditions that determine if the next lines of code should run.  Right? In your mind, you are thinking “if this and that are true, then go do this work.” That thinking drives you to wrap the business logic:

If this and that are true {

Go do the work.

}

return

I want you to invert your approach. Change your thinking to: “if this or that are not true, then bail out.” Using this inverted model, the code follows this design:

If this or that are not true {

return // bail out

}

Go do the work.

Notice that the emphasis shifts to determining if the function should continue.  If no, then the function stops executing and returns early at the point where the conditional determines it should stop and exit.

Why is This Approach Better?

This approach solves the problems listed above:

  1. The “no go” immediately stops the processing.
  2. The intent is clearly communicated.
  3. The code is more readable.

The code is clearly telling you “Hey, I’m stopping right here.”  There are no misunderstandings about what will happen. Your code is then more readable because the intent is clear.

”Multiple returns can simplify the formatting of code, particularly conditionals. What’s more, the multiple return version of a method is often a more direct expression of the programmer’s intent.”

Kent Beck, Smalltalk Best Practice Patterns

Wait, there’s more. Using this strategy, you are unwrapping the method’s business logic, shifting it back inline to the left so that as you read the code, as it flows vertically down the page.

Why is this better?  It takes less brain power to process what is happening in the code as you read and trace its control flow.

As the business logic grows, the problem exponentially grows.  The more code that is wrapped and nested, the more complex it becomes and harder it is to read and comprehend what is happening and why.

Readability directly impacts code quality.  The more readable it is, the less time it takes to comprehend, test, reuse, extend, and maintain it.

Step-by-Step Refactor: Invert the Design

Let’s invert the above code and walk through the refactoring process together.

Step 1: Invert the First Conditional

The first conditional is a “go/no go” checker.  It decides if the function will continue running or not. Therefore, you can invert it, converting it from a “go” checker to a “no go” checker.

The current design communications: “If this is a REST request, then flow into this control block.”  Invert that thinking: “If this is not a REST request, then nothing should happen so bail out.”

// Bail out if not a WordPress REST Request.
if ( !defined( 'REST_REQUEST' ) || !REST_REQUEST ) {
	return $postsOrNull
}

Notice how this design puts emphasis on (1) identifying a “no go” condition and (2) exiting immediately when one occurs. This design clearly communicates its intent of why it exists in the code.

The new design is a guard clause, as it guards the method from a “no go” and returns early when one is found.

Step 2: Invert the Next Conditional

Let’s repeat that process for the next conditional expression.

The current design communications: “If the incoming value is null, then it flows into the control block.”  Invert the approach by shifting emphasis to finding a “no go”: “Hey, if the incoming value is not null, then it’s already been sent out. There’s nothing to do. So I’m bailing out.”

// Bail out if posts were already sent.
if (!is_null($postsOrNull)) {
	return $postsOrNull;
}

Notice how this design puts the emphasis squarely on identifying a “no go” state. Like the first step, this design is clearly communicating its intent and reason to exist in the code.

The new design is also a guard clause.

Step 3: Unwrapping the Primary Code

The next step is to move the method’s business logic to the bottom of the method, after the guard clauses.

Let’s Review

Here is the code from our refactoring steps above:

public static function posts_pre_query( $postsOrNull, $query ) {
	// Bail out if not a WordPress REST Request.
	if ( ! defined( 'REST_REQUEST' ) || ! REST_REQUEST ) {
		return $postsOrNull;
	}

	// Unhook to prevent recursions.
	remove_filter( 'posts_pre_query', [ FilterWPQuery::class, 'posts_pre_query' ], 10 );

	// Bail out if posts were already sent.
	if ( ! is_null( $postsOrNull ) ) {
		return $postsOrNull;
	}

	// Mock getting posts by creating 4 mock posts with different titles.
	$mockPosts = [];
	for ( $i = 0; $i <= 3; $i ++ ) {
		$mockPosts[ $i ]             = ( new WP_Post( ( new stdClass() ) ) );
		$mockPosts[ $i ]->post_title = "Mock Post $i";
		$mockPosts[ $i ]->filter     = "raw";
	}

	return $mockPosts;
}

Go ahead and read it.

  1. It has guard clauses, each of which guard the method and stop its execution when either finds a “no go”.
  2. Reading the code, the “return early” intent is clearly expressed even without the inline comment.
  3. The method’s business logic is unwrapped and flows vertically down the page.  It is easy to identify it.
  4. The code is more readable.

While there is more we can refactor to continue improving the quality of this code, let’s save those topics for the next article.

How to Implement in Your Code

How can you implement this strategy in your code?  Look for the clues:

  1. Look for nested control blocks. Jeff Atwood calls this anti-pattern “arrow code”.  When your code looks like an arrow, it’s a big clue to refactor.
  2. If a big section of code is wrapped inside of a control block, that’s a clue.
  3. An inline comment can be a clue.  Read the comment and consider why it exists. It might be that the code is not telling you what is happening and, therefore, a comment is needed to clear it up.

When designing your code, ask yourself if the remaining code should not run if this check fails.  If the answer is yes, then stop right here and immediately bail out.

Move all pre-conditions to the top of your function, meaning validate the incoming data to determine if the function should work or not.  If no, use the guard clause strategy to protect your code.

For potential stopping points in the middle or near the end of your code, use the “return early” strategy.

Above all else, make sure your code clearly communicates its intent.  Make it readable. When you do, you will immediately improve its code quality.

Does This Strategy Work For You?

What do you think? Do you see the value of returning early? Do you agree (or not) that it better communicates intent while protecting the function’s normal control flow?

I want to hear your opinion. Share it below.

Also, feel free ask me any questions about the implementation, inversion model, or clues. I’m here to help.

Tonya is a technology leader, engineer, educator, mentor, and author.  With over 3 decades of high-tech, enterprise experience, she’s on a mission to develop professional WordPress developers and engineers at Know the Code, unlocking each person’s potential and empowering each to excel, innovate, and prosper.

The post Code Review Part 1: Fixing Design Flaw with the “Return Early” Strategy appeared first on Torque.



Read Full Article Here

Why and How to Increase Dwell Time on Your WordPress Website

Why and How to Increase Dwell Time on Your WordPress Website

Dwell time and how to increase dwell time are often neglected elements of search engine optimization. You, too, probably mostly concentrate on how to get visitors on your site and rarely give a thought about how to keep them there.

However, dwell time, the amount of time visitors spend on your site, is an important indicator. Longer dwell time usually indicates a positive user experience. It’s also something search engines take notice of.

For that reason, in this post we will dive into the topic of how to increase dwell time on your WordPress site. For that, we will first examine what dwell time is and why it matters. After that, we will shortly discuss how to measure it and finish the post with some practical advice on how to increase dwell time on your site.

What is Dwell Time (And Why Should You Care)?

The term “dwell time” was pioneered by Duane Forrester, then Senior Project Manager at Bing, who mentioned it in a blog post on the Bing Webmaster blog. Here’s how he defined it:

The time between when a user clicks on our search result and when they come back from your website […].

In short, it’s the time people consume your content before looking for more. So far so good. Why does this matter to search engines? Here’s Forrester’s take:

Your goal should be that when a visitor lands on your page, the content answers all of their needs, encouraging their next action to remain with you. If your content does not encourage them to remain with you, they will leave. The search engines can get a sense of this by watching the dwell time.

So basically, dwell time is a metric that tells search engines how well you manage to satisfy your visitors needs. If they spend a lot of time on your page, it means they like what they found and your content fulfills what they came to your site for.

Since it’s the job of search engines to provide users with the best possible search results, seeing visitors satisfied with your page is a good thing. Consequently, it would be a reason to promote your page in the search results. Conversely, a short duration could be a reason to demote it.

While dwell time isn’t an official ranking factor, you would still do well to increase it as much as you can. Why is that? Because a) there are indications that dwell time does influence search rankings and b) taking measures to increase dwell time will improve your general SEO and the quality of your site. And that can never be a bad thing.

How to Calculate Dwell Time

Before attempting to improve it, you first need to have an idea of how your site is currently faring in terms of dwell time. After all, you can only measure improvements if you have a clear before picture.

However, when you check Google Analytics or the analytics tool of your choice, you will be hard pressed to find dwell time displayed anywhere. The only thing Google offers is time on page and bounce rate.

While those are useful metrics to approximate dwell time, they are not quite the same:

  • Dwell time — As mentioned, this means the time interval between someone clicking on a search result and returning to the search page (and only the search page).
  • Bounce rate — The percentage of people who leave your site after visiting only one page. It doesn’t matter whether they spent two seconds or an hour on there, without a second click both counts as a bounce.
  • Time on page — Means the amount of time people spend on your page before moving on to anywhere else. Their next destination can be the search page, another page on your site or a completely different website.

In short, while dwell time is related to bounce rate and time on page, it’s not quite either of them. At the same time, there is no official way to measure dwell time. It’s more of a concept than a hard metric and I recommend reading Neil Patel’s detailed discussion of dwell time.

As a consequence, those two metrics are a good way to give you an indication of how your pages’ dwell time is faring. For that reason, before taking any corrective action, you’d do well to note them down for pages that you want to improve. The article cited above also gives you an idea as to what numbers to shoot for.

Effective Ways to Increase Dwell Time in WordPress

Alright, now that you know why dwell time matters and the state of affairs on your website, it’s time to take action. Trying to increase dwell time, in a nutshell, it comes down to two factors:

  • Providing an excellent user experience
  • Creating relevant, unique, valuable and engaging content

However, the devil is in the details. For that reason, here are some actionable pointers on how to do that.

Optimize the First Impression

The first thing people see on your site has great influence on whether they will stick around. If they are turned off immediately, there’s no reason for them to proceed to the rest of the page. This decision happens in milliseconds. Since you rarely have a second chance to make a first impression, you better make it count:

  • Page loading speed — 40 percent of users will abandon a site that takes longer than three seconds to load. Three seconds? That’s shorter than it takes you to spell bounce rate. Consequently, the first step to increase dwell time on your site is learn how to speed up your WordPress website.
  • Design — Web design has a lot of sway on whether visitors trust your website. That’s why you need to make sure it’s crisp and resonates with your target audience. Simple backgrounds, plenty of white space as well as clear and easy-to-read fonts are your friend.
  • Layout — Design and layout go hand in hand. Make sure your content takes center stage and is easy to consume (more on that below). You can write the best content in the world, if it gives people vertigo trying to read it, they won’t.
  • Mobile optimization — A surefire way to keep your dwell time at zero on mobile devices is to have an unresponsive website. It’s just not acceptable in today’s Internet. So, learn what makes a website mobile friendly today and put it into practice.
  • Ads and popups — While popups can be absolutely essential in building an email list, they can also be annoying as heck. Same for ads. That’s also why Chrome will begin blocking them if they are too intrusive and Google started penalizing ads last year. When using either, make sure they don’t interfere with the user experience. Use exit-intent technology and other ways for more subtelty.

Concentrate on User Needs

As explained earlier, long dwell time usually means your page is fulfilling user needs. That’s why it takes them a long time before they decide to look for additional information. Conversely, to increase dwell time, try not to give them a reason to leave. Here’s how to do that:

  • Understand your users — The first way to fulfill user intent is to understand what it is. If you can get into your audience’s heads and understand what they are looking for, you’re much better equipped to give it to them. Doing market research for your website will help with that.
  • Write longer content — Long-form content outperforms shorter pieces by a long shot. It only makes sense, as longer posts allow you to dive deeper into a topic and answer more of your readers’ questions. Although it’s more work, it also gets results.
  • Target the right keywords — The keywords in your title and description make a promise about what your piece is going to be about. If in the end you don’t deliver on that promise (e.g. an “ultimate guide” that’s only 300 words long), visitors will leave in droves. Consequently, your dwell time will suffer. Don’t do that. Oh, and stay away from clickbait headlines.
  • Keep your content up to date — Stale content is one of the best ways to direct visitors to the back button. There’s nothing more disappointing than clicking through to an article and realizing it’s horribly out of date. I personally rarely even click on search results older than two years. Others will feel the same.
  • Respond to questions and comments — the most important conversation happens in the comment section. If people interact with your articles, the worst you can do is ignore them. Not only do other people read the comments (thus staying on your site longer), when you interact with them, it’s also a reason to come back to your site.

Make Your Content Highly Readable

Readability has gained in importance in recent years. Team Yoast also gave a talk on the topic at WordCamp Europe 2016 on why they added a readability tool to their SEO plugin. Here are their recommendations to make content readable:

yoast tips for content formatting

To that, I would add:

  • Be relatable — People want to connect with other people. Therefore, don’t be afraid to let your personality shine through in your writing. Ask questions, make jokes, be a little silly. It will help others relate to your content on a more personal level and make it more entertaining.
  • Use media — Images, infographics, videos, and other media are great tools to emphasize what you are talking about and break up your content. Plus, with loads of free stock photos out there and the many services for which WordPress supports auto embeds, there’s really no excuse not to use them.

Include Internal Links

Dwell time is not just about the page that people land on. It’s also about the total time they spend on your website. For that reason, in order to keep them around longer, give them somewhere to go next.

Linking to related posts on your site (like I am doing in this piece) is one of the ways to achieve that. Another is to include a widget in your sidebar or at the end of your post that lists your latest, popular or related posts.

related posts widget to increase dwell time
Related posts here on Torque

For latest posts, WordPress has a solution built in. Good options for related posts are Jetpack and Related Posts for WordPress. Good popular posts plugins are the aforementioned Jetpack and WordPress Popular Posts.

Of course, you should also link to outside sources (where appropriate). However, when you do, make sure to open those links in a new tab or window.

open external links in new tab to increase dwell time

It’s counterproductive to try and increase dwell time on your site and then send visitors elsewhere.

Dwell Time in a Nutshell…

Dwell time is a much-debated topic in the SEO world. While it has been around as a concept for a long time, a lot of it is still unclear. Among them the question how to measure it reliably and how much weight search engines attribute to it.

However, no matter whether Google actually tracks dwell time (they probably do) taking measures to increase it can only help your WordPress site. After all, the time visitors spend on your site before returning to the SERPs is an important quality indicator. Consequently, any measures to increase dwell time will improve your site and your SEO overall.

Focus on the two pillars user experience and content. If you do that, dwell time will happen by itself.

How do you feel about dwell time as a metric for website success? Any thoughts on how to further increase dwell time on websites? Let us know in the comments section below!

Nick Schäferhoff is an entrepreneur, online marketer, and professional blogger from Germany. He found WordPress when he needed a website for his first business and instantly fell in love. When not building websites, creating content or helping his clients improve their online business, he can most often be found at the gym, the dojo or traveling the world with his wife. If you want to get in touch with him, you can do so via Twitter or through his website.

The post Why and How to Increase Dwell Time on Your WordPress Website appeared first on Torque.



Read Full Article Here

Why Your eCommerce Store Needs AMPs ASAP

Why Your eCommerce Store Needs AMPs ASAP

As you probably already know, mobile usage is on the rise. From checking the news to online shopping, mobile has become the easiest and most accessible way to get things done—partly because users can rely on their mobile devices to be available anytime and anywhere, which makes it convenient with our on-the-go lifestyles.

People are not only getting more comfortable using their smartphones to do things like shopping, they are also spending more time using them. Just from 2016 to 2017, time spent per day on mobile has reportedly increased by seven minutes, reaching a total 3 hours and 15 minutes per day. This increase in time usage represents a higher chance for retailers to sell more products online.

Search engines like Google recognize the importance of mobile usage. Thus, Google has made it a point to reward websites that are mobile optimized. Since its mobile-friendly algorithm release, Google has been pushing websites to be optimized for mobile to offer a better user experience for all.

The company’s latest initiative related to the subject, AMP or Accelerated Mobile Pages, is another step toward an enhanced mobile experience. Here, we’ll go over what AMP is, how it is helping eCommerce businesses, and why you should make the change today. Let’s get started!

What Is AMP?

AMP, as mentioned, stands for Accelerated Mobile Pages, and it’s a relatively new open source project created by Google to accelerate the loading speed of mobile sites. AMP pages are built with three components: AMP HTML, AMP JS, and AMP Cache. These components help deliver a much faster performance than regular mobile-friendly sites, which makes for a better overall experience.

In fact, Google claims that they are so fast that they appear to load instantly. It’s like having the same look and feel of your site but with a much “lighter” code that enables faster load times. The AMP project site offers many guides and resources available for even the most non-tech-savvy users. However, if you want to skip the learning period, there are many plugins available for major CMS platforms that make the process easier to handle.

How AMP Can Positively Impact Your eCommerce Business

AMP pages were early adopted by news-related sites and eCommerce giants like eBay. The company rolled out millions of AMP pages to speed up mobile loading times. Content-related sites are also seeing the benefit of using AMP. As you can see below, Google is featuring them in a carousel format (note the AMP line below each article in the carousel).

Thus, Google is giving these sites more visibility and, in turn, higher traffic. Although eCommerce sites haven’t benefited from this carousel feature yet, AMP pages can still provide many benefits to this industry. Let’s go over them below:

  • More visibility. Google gives preference to sites that load faster by increasing their organic ranking. Having AMP pages will give you the competitive advantage to rank above your competition while providing a better user experience for your visitors.
  • Reduce bounce rate. Do you know that almost half of your visitors will abandon a page that takes more than three seconds to load? This means that if your pages are taking too long to load, you can experience a higher than usual bounce rate.
  • As defined by Google, bounce rate is “a single-page session on your site … such as when a user opens a single page on your site and then exits without triggering any other requests to the Analytics server during that session.” AMP can help you reduce bounce rates by speeding your loading times. In turn, lower bounce rates also contribute to higher organic rankings.
  • Higher returning rate. One of AMP’s case studies which features The Washington Post states that the news site received a 23% increase in returning users from mobile search. Also, they experienced 88% improvement in load times. What made them return?

 

 

Considering that nothing else changed, it is safe to say that faster mobile load times produced a better user experience, which encouraged visitors to come back to the site. In a similar way, the enhanced experience enabled by AMP, can incentive your eCommerce visitors to come back to your site for repeat purchases, thus increasing your potential revenue.

 

  • Higher conversions. Having faster loading times will provide your customers the ideal experience to encourage eCommerce conversions. It will also allow them to find the products that they are looking for faster and prevent second-guessing. The more products they view, the higher chances you’ll have of getting higher order amounts.

 

Cons of Using AMP

As with anything else, AMP also has its cons. Let’s go over them below:

  • Google Analytics Issues. AMP requires a different Google Analytics tag that has to be implemented on every single page. This can be very time-consuming and tedious. Also, you may not be able to see all the usual charts and tables offered by Analytics.

 

  • Ad Revenue Is Reduced. This point doesn’t really affect eCommerce businesses that much unless your store is connected with a blog where you advertise other sites. AMP supports ads, but the implementation is not easy and others have experienced a decrease in revenue of this department while using AMP.
  • Limited Functionality. For the sake of increasing loading speeds, you may miss some higher level functionality that can be implemented with regular responsive designs.

 

Final Notes

AMP offers pros and cons; however, the pros seem to outweigh the cons when it comes to eCommerce. It can offer your store increased visibility by possibly boosting organic traffic, reduce bounce rate with high loading speeds, and increase conversions. If you have the time to learn how to implement AMP or if you have a resource that can help implement it, it’s definitely worth a shot. Implementing it sooner rather than later can also give you a competitive advantage over other stores that are not mobile friendly or which simply have a responsive design. Who knows? Maybe AMP will become a must-have in the upcoming years.

The post Why Your eCommerce Store Needs AMPs ASAP appeared first on Torque.

Read Full Article Here

Things You Should Know As A Freelancer WordPress Developer In 2018

Things You Should Know As A Freelancer WordPress Developer In 2018

There are many ways to improve freelance web developer revenue. The holy grail may be hidden somewhere between sales process improvements, creating better proposals, and changing the pitch. Sometimes the key is actually to offer products that do not require pitching at all.

Let’s go through a few ways to get noticed and start making money.

Drive Toward The Need

Changing the way web developers position themselves is an excellent first step on the journey to making more money. The crucial part here is to understand what’s driving customers to purchase. Why do they even want to have a website?

Here is a list of pain points many web owners face:

  • Delays in a project
  • Ditching the project by the web developer
  • Being left on their own after the project
  • Being asked questions that require technical knowledge that they don’t have
  • Lack of vision / Not being able to explain my idea

As you can see most of these issues are not about the website itself but about the way a website project is organized. I have discovered throughout my years in the web development business that value propositions that highlight the advantages of project organization more than code quality itself resonate better with the customers.

The reason for it is that it’s hard for a customer to compare the quality of different web developers because it requires technical knowledge most clients don’t possess. That is why, it is way easier to differentiate from the competitors not by underlining the code quality, but by showing competence in organizing a website creation project.

Once you know the pains, you know what the key points to highlight in the proposal are. Answer those pains and remember to drive directly toward their need. Your proposal will be too compelling to refuse.

Sell Benefits

Don’t sell advantages of the website you are about to build. Describe the benefits for the site owners and explain what they will gain by working with you on the website development project.

For example, instead of promising a responsive layout, tell them that the site will be readily available on a hand-held device. This way you underline the gain a customer gets from it and, at the same time, you avoid speaking in jargon.

Apart from feature-related benefits, there is also the positive effect on project management. One of the best deal-sealing benefits that I leveraged throughout my career in website development was assuring the customer that I would clarify his vision and transform the idea in his head into a fully operational website. The success rate will only increase if you have found in the pain discovery phase that a customer has this problem.

Working With Prospective Customers

It’s not just about building websites for whoever comes. It’s about investing in relationships that will keep you fed in the long run.

I often told my customers that I don’t build websites. I told them that I can take care of their online presence, make sure that their business will look professional, and help them receive customers of their own. Of course, a website played an important role in the overarching strategy, but the point was to get more jobs from serious people who were committed to getting the most of their online presence. As their vision was evolving and growing, they had more and more need of my services.

Another tactic that I found to be very successful is to focus on customers who are looking for long-term relationships. Instead of offering to build a website, provide development and management combined. Sometimes I even suggest to not create any website at all but to refresh and maintain what the client already has, which gave me a massive advantage over the competition. Adding the management part to your proposal not only increases revenue per customer but also assures your client that you are not going anywhere and you will be there for them, which is another critical pain they usually have.

Collect money the smart way

Your accountant may disagree, but it is cash flow, not profit that drives freelance business. It is great to have a five or six-digit contract signed, but until you get it wired, you can’t pay bills with it.

Here’s a set of tips and tricks that helped me stay cash flow positive in both my freelance and agency times.

Collect Often and Early

Taking 30-50% of the money upfront is a standard way of improving your cash situation, as your position at the beginning of the project is much stronger than near its end. Additionally, I used to divide projects into stages (such as: accepting the website mockup, accepting the website graphics, etc.) and charge a chunk of the total price after completing every stage. This way I had to collect no more than 30% of the price at the end of the project.

Organize The Approval Process

No matter how much money you will collect upfront or during the project, almost always there is an amount due only after a customer has approved the project. That’s what makes organizing the acceptance process crucial. The secret is to specify the scope of the project in the agreement (You can download a sample description of a project’s scope from Perfect Dashboard).

Scrum is rarely possible in the low-end market most of us work in. The more specific you are, the less wiggle room you leave for interpretation and misunderstandings. What is more, I used to limit the time for each round of testing and added a provision that in each following round a customer could only report bugs there weren’t there in the previous. When I implemented this idea into my business, I had the project acceptance time reduced by more than 50%.

Keep Control Over The Website Until Paid In Full

It’s all about keeping an advantageous position. Once the site is fully operational and it’s on the customer’s hosting, there’s not much you can do get your full compensation apart from going to court which is often not even an option, especially if you deal with foreign customers.

That’s why some freelancers keep administrative access to the website until it’s paid in entirety, so they keep the option to turn it off just in case. I used to do it the other way around. I turned on the website’s front-end only after I got all the money. This way I was able to avoid further escalating the situation by turning the site off and still keep some control.

Use Auto Collecting Solutions

If you don’t feel like collecting money, then you could always use a third party service like peopleperhour.com or freelance.com. In such a case, the money for your project is secured by a third party. They can also be helpful in conflict resolution.

Avoid Changes In The Website Project Scope

Several techniques can help you prevent or decrease the chance of project scope change. The rule of thumb is that every hour spent on specifying the requirements before writing the first line of code saves you ten hours afterward.

Get The Customer Involved Early

How many times have you delivered a complete website to a client for review and approval only to learn that it has nothing to do with his actual needs? That is why it is crucial to engage the customer in the early stages of the project.

The earlier you demonstrate a mock-up, a draft of requirements or any other thing that specifies the project scope, the bigger the chance that you will avoid wasting your precious time on things that are not what your customer wants. Whenever you get the customer involved there is an opportunity for valuable feedback that will make it possible for you to save your time and create a website that is precisely what your customer needs.

Make sure the customer is involved in the process. Every time I heard that they had no time to review the draft I sent them, but that they are sure that I will build a great website for them, I took that as a bad sign. Nodding heads are a red flag. If they say it’s okay – ask questions. Ask them what do they think about the mobile version. Make sure they reviewed what kind of content they need to deliver on their own. Explain to them that the website will look differently at various devices and browsers. Once again, every hour spent with the customer before writing the first line of code saves 10 hours spent on the acceptance process later on. Trust me. I’ve been there, I’ve done that.

Create Mockups / Wireframes

Create a simple sketch of the project to help a customer visualize the layout(not graphics) of elements on the website and the navigation structure. This way you can make sure that both you and your customer think about more or less same website before you dive deep into coding. I’ve been using UXpin to this end, but you can easily find dozens of similar tools out there. This is especially essential if you are working on a responsive website.

Clarify Customer Vision

This is where experience in both web development and psychology comes in handy. First, when customers described their vision I often asked: “why is this important to you?” You wouldn’t believe how many myths about what is right for SEO, security, or website traffic are out there.

Asking this question gives you a chance to educate your customer on the current state of the art and explain that displaying white text on a white background is not a necessarily the best way of getting more traffic from Google. Secondly, I used to ask a list of routine questions that included:

  • Who is your typical visitor?
  • What is the goal, that the visitor shall achieve while on the website?
  • Do you plan to regularly add content to the site?
  • Which social media do you want to integrate with?
  • What type of social integration do you have in mind? Is it liking/sharing or something else?
  • Will you be adding/changing content on the website yourself?
  • What kind of devices will a visitor use to access the site?
  • What interactions will be possible on the site (apart from reading the content)?
  • Will there be any contact information provided? In what way?
  • Do you need to connect the website to any other software/service?

Document the requirements

Write down the requirements and attach them to the agreement. Scrum and other agile methodologies are a great way of developing new code, but they are difficult to understand regarding billing for a customer. I suggest an old-fashioned, written document with as many details as possible. A sample requirements document template that I was using in my freelancing days can be found over at Perfect Dashboard.

Organize The Acceptance Process

A neatly organized acceptance process can save you a lot of time and avoid becoming a nerve-wracking experience for both sides.

It all starts with writing down the requirements. This way there is something to compare the website with. I always tell my customers to open the requirements documentation and note point after point whether everything stipulated there is reflected on the site.

Secondly, if they had some feedback I always ask them to submit it on the margin of the initial requirements documentation. This made it difficult for them to add features that were not originally there as they couldn’t find a right place to write them at.

The third thing is to limit the time for testing to some reasonable amount of time since the website has been made available for testing (I used seven days). Lack of feedback within the agreed period means that the project is accepted as it has been delivered and I can send an invoice right away. I tried to stay flexible with my customers, but there were a few times when I used this mechanism to invoice an unresponsive customer.

Another thing is to organize website testing in rounds. Ask the client to submit all the feedback all at once, not to drop one email after another. Once they are done with the first round of feedback, review it to make sure it’s not a change of scope and then apply it. After that, it’s time for another round of customer testing and possibly another round of your fixes. This lasts until a customer accepts a website without any comments. It may sound formal and impractical, but believe me, it saved my hours in my freelance times.

Aleksander is CEO of Perfect Dashboard. A frequent speaker at WordCamps, Hosting Events and Joomla Days around the world. Originally from Poland, this foodie & computer games freak is very excited to blog on Torque!

The post Things You Should Know As A Freelancer WordPress Developer In 2018 appeared first on Torque.

Read Full Article Here

The Hidden Gems Of WordPress

The Hidden Gems Of WordPress

One of the most frustrating things about WordPress is that parts of the WP Admin are difficult to find – if not outright hidden. That makes getting things done not so easy or intuitive.

But as with any application, some elements of the User Interface need to be hidden or obscure for various reasons. Usually, it is because a function or feature is not frequently needed until it is. That’s when the hair pulling begins.

Don’t end up hunting around for that WP Admin element as if you’re looking for lost treasure. Here are the most common hidden gems of WordPress that sooner or later you’ll need to use.

All of the following are a part of WordPress Core and have nothing to do with what your theme or any plugin may add to your WP Admin.

WP Admin? That’s where you end up when you log into your site.

Screen Options

This is a little gem is hidden in plain view.  In the upper right-hand corner of just about every page in your WP Admin is a Screen Options button. It’s the way to modify whatever is on that page.

Here are some examples of what Screen Options are.

Drag And Drop Features

Did you know that parts of the WP Admin can be moved around to suit your needs?

I left out moving menu items and widgets into place because that’s probably more intuitive than what I showed in my video.  And keep in mind that some plugins have draggable elements that may not be so easy to see at first glance.

Hovering Over

I assume you know that you need to hover over the links on the right side of your WP Admin to see submenus. But did you know about this?

Not shown in this video, is that the same thing happens when you look at the list of your users. You’ll need to hover over a user’s name to edit or delete a user account within your site.

Bulk Actions? Say What?

Ever wonder what Bulk Actions do? When I first started with WP, I didn’t use it for a long time because I could not figure out what it was or how to use it.

I think it’s a bit obscure and not so intuitive. In my video, I show you how to use it to save time when working with multiple pages or posts simultaneously.

You’ll see Bulk Actions show up in various places in the WP Admin.  It’s a great way to update all of your plugins in just a few clicks.

What About Gutenberg?

This Spring, WordPress will roll out an entirely new editing system. It features a very clean workspace without a lot of UI that is hidden until you hover over some part of it.

The key concept behind Gutenberg is the use of blocks which allows various types of content to be inserted into blocks. In the years to come Gutenberg will usher in entirely new ways to create content and developer websites. Stay tuned!

Conclusion

What may be obvious to some WordPress authors, may be completely hidden or confusing to others. While that’s true to the design of any user interface, WordPress presents its own unique challenges. Overcoming those challenges will make it easier and more satisfying to use WordPress.

Bud Kraus has taught web design and WordPress for over 20 years in New York City and for his online students. He is the creator of the WP A To Z Series, a free WordPress training service. He works with small businesses and their sites too.

The post The Hidden Gems Of WordPress appeared first on Torque.

Read Full Article Here