CAll Us: +1 888-999-8231 Submit Ticket

Adding Unit Tests to an Existing WordPress Plugin

So far we’ve done little more than introduce you to the idea of building tests for your WordPress plugins and talk about a bunch of the extra terms you need to understand to dive deeper into testing your code. Today we’re going to make it practical by grabbing one of my free plugins and adding a few unit tests to show you how to put it together. 

You can find the plugin on Github or Just like my previous post, I assume that you have WP CLI installed and can set up basic tests. If you can’t check out my post introducing you to unit testing in WordPress.

Unlike the last time, we only need to scaffold the tests so we can start with the following command in our WordPress installation.

wp scaffold plugin-tests wptt-ics-feeds

Now let’s get into writing a few tests.

The first thing I want to test is to make sure that the links a user sees in their profile with calendar feeds are correct. Specifically, we’re going to look at the get_subscribe_link function.

You can see the completed tests for this section here.

Let’s start by copying the default sample test file and renaming it to test-feed-links.php. I always like to create different files for the areas of the plugins I’m writing tests for, even if that means I have lots of files to deal with. It’s far easier to stay organized with clearly labelled files.

This plugin is a bit older and instantiates a global variable as it starts up. This allows us to call that global when in our setUp function so that we have access to the plugin code. We’ll also need to use the WordPress Factory to set up a new user so that we can test the links provided with that user. That means our setUp and tearDown functions should look like this.

public function setUp(){


    // getting the plugin global

    $this->plugin = $GLOBALS['wptt_ics_feeds'];

    // make a fake user

    $this->editor = new WP_User( $this->factory->user->create( array( 'role' => 'editor' ) ) );


public function tearDown(){


        wp_delete_user( $this->editor->ID, true );


Now we can get to writing a test for our feed links. We’ll write two different tests to test both situations that the link function can find itself in. First, we’ll test get_subscribe_link() without any arguments.


     * Tests base feed link without author


    public function test_base_feed_link(){

        $feed_link = $this->plugin->get_subscribe_link();

        $complete_link = site_url() . '/?feed=wptticsfeeds';

        $this->assertEquals( $feed_link, $complete_link, 'The feed links are not equal' );


The first thing the code above does is access our plugin instance as defined in the setUp function and call the get_subscribe_link() function. Next, I hard code the expected output of the function so that I have something to compare against. Finally, we use assertEquals to compare the two values.

With that done I can head back over to terminal and run the tests with the phpunit command. If my tests pass I’ll see something like the output below. If they don’t pass then I’ll get a big red warning instead of a green bar, which means I need to figure out why they aren’t passing and fix the tests.

In this case, our tests passed and we can move on to testing the output of our link function if we pass in an author name. You can see this test below.


     * Tests feed link with author


     public function test_author_feed_link(){

        $feed_link = $this->plugin->get_subscribe_link( array( 'author' => $this->editor->ID ) );

        $complete_link = esc_url( site_url() . '/?feed=wptticsfeeds&wpttauthor=". $this->editor->user_login );

        $this->assertEquals( $feed_link, $complete_link, "The feed links with author are not equal' );


Here we do almost the same thing as we did when we tested our link previously. The change is that we pass in the user we created with our setUp function and then test to make sure that this link comes out as expected with assertEquals.

Now, let’s move on to testing the custom filter inside the plugin.

Testing a WordPress Filter with PHPUnit

I’ve had some disputes with other developers about testing filters in the past. Some don’t bother testing their internal plugin filters, but I think that you should be testing these filters. Sometimes filter names change and you forget about this so don’t document it anywhere or check for usage of the filter. Writing a simple test for your filter will highlight this because when you change the filter name a test error will happen.

For this test, we’ll add a new file to our tests folder called test-filters.php. I’ll use this file to test all future filters that need to be tested in the plugin. This time our setUp function only needs to instantiate an instance of our plugin and our tearDown function doesn’t need to do anything. See the code below.

   public function setUp(){


        // getting the plugin global

        $this->plugin = $GLOBALS['wptt_ics_feeds'];


    public function tearDown(){



Next, we need to write the test for our filter which you can see below.


     * Tests that the post where time can be changed with a filter


    public function test_posts_where_filter(){

        add_filter( 'wptt_ics_feeds_how_old', array( $this, 'new_where' ), 10, 2 );

         $output = $this->plugin->two_months( '' );

         $date = date('Y-m-d', strtotime( $this->new_where() ) );

         $this->assertStringContainsString( $date, $output, 'The date filter did not work' );


    public function new_where(){

        return '-1 week';


The first thing we do is call our filter and then pass it our new_where function. I always like to write a separate function for filter tests because I have ended up using them in multiple tests enough that I feel this saves work later. Our new_where function will pass the string -1 week to our filter.

Next we call our two_months() function inside the plugin. Then we use a standard PHP date function to get the format we expect for the date. Since I’m mostly concerned that the date is parsed properly in the plugin I use assertStringContainsString to check to see if the output of the two_months function contains the same date string as the $date variable.

Again, if your tests pass, then it should all be green. If they fail you’ll get a big red warning instead of the pleasant green bar.

Why Don’t We Test the ICS Feed Output

Note, that I didn’t test the final output of our ICS feed. While this is possible, it’s got a bunch of moving parts that could fail and have nothing to do with my code. I could send the ICS feed to an online validator and then receive the JSON response and parse it to check if it’s valid.

If the HTTP request fails, my test fails. If the online validation service shuts down, my test fails. There are a bunch of other scenarios that could also cause my test to fail for no reason that’s my fault. Because of this, I chose not to test the final feed programmatically and figured that I could test it by subscribing to a feed in my calendar and seeing that my posts were in fact on the calendar as expected.

This Isn’t Unit Testing

I’m sure that some of you are looking at this and saying that I’m not writing unit tests, and you’d be correct. I’m writing integration tests because my code is integrating with WordPress for the tests to work. Yes, you can use WP_Mock to fake WordPress to write true unit tests, but most of the time I care that my code works with WordPress.

Today, we looked at adding a few tests to an existing WordPress plugin as a practical example of how testing can work for your projects. To continue learning, check out the business case for adding testing to your process as a business owner. It can be hard to see past the upfront expense since development will take longer, but it does pay off.

Source link

75% Off 3 Months of Managed Hosting: Position Yourself for Your Best Year Yet with Our Best Deal Ever

In 2020, a year that has been so hard on so many businesses, we are grateful for the resilience and determination of the agencies, sites, and stores that rely on Hostdedi. 

Thank you for being our customers.

2020 Was a Game-Changing Year In Ecommerce

Let’s face it – 2020 was BANANAS. In this year alone, small businesses took massive hits in revenue, and nearly 100,000 closed their doors for good. Others have thrived.

Adaptability and resilience has been the name of the game for 2020. As brick and mortar businesses closed their doors due to COVID, ecommerce sales surged. Total online spending by May had skyrocketed by $52 billion, a 77% year-over-year increase.

This year was also an unexpected boon for ecommerce developers. In an industry already rife with demand, ecommerce development agencies saw an increase in demand for new websites. The total number of ecommerce sites, as of this year, now stands at over 24 million.

Where Ecommerce Companies Are Still Losing Revenue

The caveats to success in ecommerce are still there, however. Pages that load in more than three seconds deter 40% of traffic, and an estimated $18 billion in revenue per year is still lost due to cart abandonment.

Ecommerce is thriving, and the opportunity is growing rapidly. By 2040, it’s estimated that 95% of all purchases will be made online. That is astounding!

The problems with ecommerce still exist though, and now more than ever, it’s time to ensure your digital commerce site is speed optimized for conversions.

Positioning Yourself for Your Best Year Yet

No matter how wild it gets out there, Hostdedi is going to keep on giving you hosting you can count on. That’s been our focus throughout this crazy year – continue innovating, keep your sites online and safe, maintain fair prices, and keep providing the tools you need to stand up a new ecommerce shop, or maintain an old one. 

This Black Friday, we’re gonna keep on keeping on by offering our customers our BEST SALE EVER. This is truly one for the record books, folks. Hostdedi has never offered a discount this deep. 

We’re offering an unprecedented 75% Off 3 months of our most popular plans with code JOYFOR2021.

No matter what happens in 2021, you can count on Hostdedi to keep making it easy and affordable to start your own online business or migrate to a hosting provider who is a true partner in business.

Source link

What’s the Difference Between WordPress Hosting & Web Hosting?

When searching for a web hosting provider, you’ll find a lot of different options and deciding which to choose can be overwhelming. WordPress is usually a safe bet when starting out with a website – it offers a simple but powerful set of tools to get you started in no time, and because of its flexibility and ease of use, it already powers 35% of the Internet (source)

But where exactly should you run WordPress? Let’s take a look at the two most popular options for making a website available: shared hosting and Managed WordPress hosting, and the advantages and disadvantages of each.

What is Managed WordPress Hosting?

Managed WordPress Hosting is a specific type of shared hosting, which has been tweaked and modified to improve the hosting experience specifically when using WordPress websites. The “Managed” part is important too, because it means that there’s staff on board taking care that everything runs smoothly.

Specifically, Managed hosting adds support for the operating system and application infrastructure. In other words, your host will make sure that WordPress is up-to-date and running correctly, so you can focus on creating the content of your site.

The exact scope of managed support varies between hosts, especially when it comes to heavily-customized sites with a large number of plugins. In general, a best-effort policy applies – even if you’re having trouble with a very complex setup, the experts managing your site will attempt to help with it, and point you in the right direction if needed. 

What are the Advantages of Managed WordPress Hosting?

Faster WordPress Performance: As the name implies, Managed WordPress hosting is specially built to handle WordPress-based websites, both in their PHP settings and on their database setup. This translates to a much better performance than with generic settings. This is all out-of-the-box, so you can get to creating your site immediately without spending much time dealing with configuration. 

Better Security: Security is also a great positive of Managed WordPress hosting, since services that aren’t necessary for WordPress are disabled, and common attack points (such as xmlrpc.php) are taken into consideration.

Better Resource Scaling: Managed WordPress hosts can also scale up and down on-demand to accommodate a sudden spike in traffic, since the site doesn’t have to live in a single server. That way, one of your posts suddenly getting a lot of attention will not punish you by bringing your entire website down. 

Better Support: In addition, the staff on hand has much more experience dealing with WordPress, so they’ll be empowered to help with any issues you may face.

In short, Managed WordPress hosting is a higher-quality option when it comes to hosting WordPress sites.

What are the Disadvantages of WordPress Hosting?

Higher Cost: Because of its quality and additional features, Managed WordPress hosting is a premium option, which is reflected in the price tag. For multiple small project websites where you don’t expect much traffic, this can be overkill, much in the same way that you wouldn’t rent a spot in a shopping mall for a lemonade stand. On the other hand, if you’re looking to launch your business or move an existing WordPress site to a more reliable host, the benefits more than outweigh the costs.

What is Shared Hosting?

Shared hosting is the most basic option for getting a website online. In short, it is when you rent some space on someone else’s server to host your website’s files, and then point your domain name to that server. There are many types of shared hosting options available, but in the most common form it is a spot to place your website’s files so they’re served when someone visits. 

Something to keep in mind is that shared website hosts handle many different kinds of websites with varying resource needs, which all share a portion of the same resources, so performance settings are usually generic options that fit most websites reasonably well. 

What are the Advantages of Shared Hosting?

Affordability: The main advantage of shared hosting is how affordable it is compared to other hosting options. Since your website is hosted on a shared server, it doesn’t cost the hosting provider much to add one, or a dozen more websites, especially if these are small sites that don’t receive a lot of traffic. That makes shared hosting ideal for small projects that aren’t expected to get a lot of attention, and for quickly trying out new ideas you get. 

What are the Disadvantages of Shared Hosting?

Here are the three most common disadvantages of shared hosting across most shared hosting providers:

Compatibility Issues: You need to make sure your content management system, or CMS, works well within the shared hosting environment. This includes making sure the PHP and MySQL versions are compatible. Your host’s support can often provide some help with that, but only up to a point – considering the many different types of websites they will be hosting, in-depth knowledge about every single one of them is a difficult proposition, so you might end up needing to get a developer on board for very difficult problems.

Software Updates: Software updates are another common pain point in shared hosts, which can break your site if its code relies on features from older software versions. Some hosts have features to alleviate this, such as letting you choose the PHP version you want to run your site with, but running older software is not recommended for security reasons. After all, software versions that are out of support no longer receive security updates, rendering them potentially exposed to newly-discovered vulnerabilities.

Shared Resources: Since one server is shared across all the websites hosted in it, the performance of your site can take a hit during peak times, even if your own site is not getting a ton of traffic. This is compounded by the fact that shared hosting is usually configured with generic performance settings, not optimized for any particular kind of website. 

Choosing Between WordPress Hosting vs Shared Hosting

It is important to use the right tool for the job, and if loading speed, ease-of-use, and availability are critical for you, then Managed WordPress hosting is a useful tool to consider. Our plans have a lot of additional features not offered in most Managed WordPress hosts, such as full server access, automated staging sites for testing plugin updates, and 24/7/365 support by phone, email and chat. 

If you’re a more advanced user who’s comfortable with server management, and you’re looking for more freedom to go along with that responsibility, a VPS package might be good for you, which you can compare to our Managed WordPress options. 

Finally, if you’re still on the fence about what would work best for you, you can always chat with one of our experts for help picking the right plan.

Source link

Doing Product Pages Right – Hostdedi Blog

How much effort have you put into your product page? Yes, I know you found information and images from the manufacturer and added them. Sure, you named the product and maybe if you were really working on good product pages, you took an extra picture of the product in use to highlight what it really looks like to your customers.

But I know most ecommerce sites don’t even go that far.

About 10 years ago I worked in retail and one of my jobs was to add products to our site, but only after everything else was done and if the boss couldn’t find anything extra for me to do. This was shortsighted and meant that they didn’t see much business from their online store. But if you don’t put any effort into your product pages, the natural outcome is little traction with your site.

It’s important to remember that your online users can’t touch your product. They can’t ask a salesperson a question or get specific feedback on how the product worked for someone they can talk to. Customers are reliant on the information you provide them to help them make a purchase.

Today we’re going to talk about how to design a great product page. Remember, from the product name to the reviews, your product page is a landing page. Its job is to sell your products to your customers.

Product Name

If your product page is a landing and sales page, then the first thing you need to look at is the name of your product. This is the title of your page and you should spend just as much time thinking about this as you would for any blog post you want to rank well in search engines. The more descriptive your product name is, the better it is, at least up to a point.

We’ve all seen ridiculously keyword-stuffed Amazon product titles. We want to use a descriptive product name, but not crossover into the realm of these overloaded titles.

Take a look at these Mpow headphones on Amazon.

If you’re looking for waterproof Bluetooth sports headphones with controls on the headphones, the title is a great match. I think it’s getting close to being a bit long, but just by reading the product name, you get a summary of all the features that the headphones provide.

When you’re looking at your product names use the Google Keyword Planner to investigate what terms are ranking well for your product. Use these terms to help you craft a well-optimized title that will bring customers to your landing page.


When it comes to your product description, the first thing to ask yourself is “what questions will myom customers have”. A description that answers your customer’s questions poorly will mean they make a purchase they’re not happy with. Then they’ll want to return it, and you may get a poor review on the product.

According to Nielsen Group, 20% of missed purchases were because a product didn’t have the information a customer was looking for in the description. If users don’t see the information they’re looking for in your product description, they’re going to turn to Google. That means you risk having them find the product at a better price elsewhere. Making your customers search to get more information is just like losing the purchase and all future purchases from your customer.

As you write your product description ask yourself what questions the customer will have about your product? Your goal is to answer the questions and deflate the objections that customers will have so that they feel confident in their purchase.

Good product descriptions are jargon-free. They’re not heavy on marketing text, but are to the point and clear. If you’re talking about 5 different feature highlights, use bullet points so that readers can scan to get the information they need quickly.

If you’ve got many of the same types of products, say dishwashers, then take the time to standardize the language across suppliers. Don’t list measurements in inches for one product and then centimetres for other products. Standardize on one method, or if you deal with international clients let them choose what measurement they want to see. You can see a great example of this with Apidura Cycling bags. They let users change between inches and centimetres for their bag measurements. This puts their users in control.

Product Images

After your product name and description, it’s important to focus on the images you provide to your customer. Remember, they can’t touch the product. They can’t tell how big it is, or exactly what shade of blue it is. They are relying entirely on you to provide this information with your images.

There are two ways to go with product images. You can choose to use a backdrop with other stuff that matches the product, or you can go with a flat white version. Keep the style consistent including the dimensions used with the final images. I think the best option is to have a combination of both of these options.

Bellroy is a great example of both methods combined. They show you several images of their products on a flat white background. They also add it with known items, like physical bills and blank cards that are the same size as credit cards. You get to see high-quality uncluttered photos to judge colour and texture, then clean photos that help you get an idea of the size of items you’re looking at.

Bellroy also provides high-quality images for each color option for a product. You don’t have to guess based on a color swatch, you can see exactly what you’re choosing as you make changes.

While this may look like a lot of work, it’s just a bit of work and a small investment. You don’t need a fancy camera. Any smartphone in the last few years will do. If you don’t have natural light, then you will need to purchase a consistent light source. You can usually find the Godox SL60W for under $200. If you’re dealing with small products and want to have an extra clean background, then look at a softbox. You can find these on Amazon for as little as $30.

With a light source and a softbox, all it takes is a bit of practice. Take a bunch of test images from different angles. If you spend a weekend playing around you’ll improve greatly so that you can get good images for Monday.

If you’re looking for a great walkthrough on product photography, check out the video below by Peter McKinnon.

Once you’ve got the images, take a few minutes to edit them for color and contrast. Most people use a sized template so that every image on the site is the same size. 

If you’re not sure what this means, it’s like having a company letterhead you always use. In this case, it’s a Photoshop file that’s 2000X2000 and every image you take goes on the same template so that your site images look uniform. 

Then once you have your images on the template looking how you want them, save them out in a web format. Look to keep them under 700kb if possible. To help with this at the final stage you can use tools like Kraken to optimize the images as you upload them.

Putting some effort into your product images will help your store stand above the competition.

Adding To Cart

Next, your add to cart button. There are a few mistakes that many sites make with this crucial interaction. First, make sure that users can see the button without scrolling across all devices. It should be obvious and a contrasting color from the rest of your site so that it stands out. You can see a good example of this on MEC below.

Note that they have a nice product image, and the purchase button is in a vibrant green and stays with the customer as they scroll on a mobile device.

You also need to make sure that it’s clear to the user something happened when they add something to the cart. Luckily WooCommerce has this as a default with a banner being displayed to a user after a product has been successfully added to the cart.

The second most important interaction after your main purchase button may be the option to add a product to a wishlist. A good spot for this is just below the main purchase CTA. I have many wish lists on Amazon for when I’m ready to revamp parts of my office. I already have my desk video setup all picked out in a wishlist. When it’s time to purchase I just need to add all those products to my cart, and then checkout.

Showing your product in use can show how easy it is to use to customers that are concerned about that. Yes, it might mean some duplicate information, but highlight the benefits and deflate the objections with your videos, just like you do with your marketing copy. Some studies suggest that a good product video increases conversion to sale by 84%. Videos are also known to have higher click through rates in search.

You can see this if we head back to Bellroy. The first thing that comes up with their products is a video of their product in use. 

Just like good product photos don’t have to be a huge investment, decent video doesn’t have to be a huge investment. The light I recommended above is a great video light. Your recent smartphone is a decent video camera. Add a lavalier microphone to this setup for $50 and you’ve got a good video setup.


When it comes to pricing, it’s pretty straight forward. Make sure you don’t hide any price increases from your users. If the blue version is more expensive, change the price when the user selects the blue version (don’t worry both WooCommerce & Magento do this out of the box). Just under the price is also a good place to add product availability information. Don’t let your customers try to add something to the cart only to find that the product isn’t available in their chosen combination of size and color.

Social Proof: Reviews

Did you know that user reviews are 12 times more powerful at convincing people to purchase than your marketing copy is? That means you need to employ ratings on your site. Display the overall rating, usually stars, at the top near your product title and description. Then after all the product information your customers want, display the reviews you’ve gathered from users.

It’s important to make your reviews filterable, and don’t censor bad reviews. I’ve often read the bad reviews for a product to find the pain points and then purchased because I don’t care about any of the major issues with it.

One great plugin to help enhance the reviews on your site is WooCommerce Product Reviews Pro. This plugin will let you add product photos and user videos to your reviews to supercharge your social proof.

Remember, your product page is a landing page and should be optimized for search engines and to convert visitors to customers. As I said when I talked specifically about mCommerce, make sure that you A/B Test the changes you’re making to your product pages to help ensure that they’re having the effect you expect. If you can put a bit of effort into your product pages, you’ll see big rewards in your sales.

Source link

The Top 5 SEO Plugins for WordPress Compared

Whether your WordPress website is a personal blog, ecommerce store, or hosting website, choosing the right SEO plugin shouldn’t be ignored. In this post, we’re comparing the top SEO plugins for WordPress, so you can learn how to best optimize your site for search engines. Doing this the right way will improve your search visibility, page and post ranking, boost your traffic, and improve your sales. 

You may have heard about the Yoast SEO plugin by now which is currently the most popular All-In-One SEO tool for WordPress.

But, did you know that there are also other well viable options on the market as well? SEO Optimization tool Rank Math has built a huge and successful community in a short period.

This proves that while you are building your fantastic website with quality content, ready for visitors to consume, you don’t have to think about things such as; will anyone see my content or if my website is good enough.

With so many great solutions out there, driving the website traffic has never been this easy.

In this article you will learn the following:

  1. What are SEO Plugins for WordPress
  2. SEO tips everyone should use
  3. 6 Best SEO Plugins compared

Let’s get started!

What are SEO Plugins for WordPress

The great thing about SEO plugins is that even if you are not SEO-savvy, you can still take advantage of the latest SEO tweaks. They provide a great all-in-one solution for the end-user.

All you have to do is choose the Plugins option on your WordPress Dashboard, click “Add New”, type the name of the plugin in the search bar, Install, and Activate.

Most of these SEO Tools come either with a free version and optional premium version as well. Just keep in mind that none of these tools is a perfect “do-it-all” option. 

There are a lot of other things to consider when it comes to search engine optimization such as keyword research.

This brings us to the next chapter.

SEO Tips You Should Consider

Even though all-in-one SEO tools are great, there are other important things you have to do as well.

If ranking high on Google and other search engines was easy as walking, everyone in the world would have a successful website and do this.

Since that is not the reality, and the majority of published posts don’t get any traffic, here are some useful SEO tips that we recommend.


This is the most important step to take. There are many great free and paid tools that will ease your keyword pursuits such as Ahrefs and Ubersuggest.

Once you have found a niche with relatively low competition you are ready to go. Oh and don’t forget to export as many keywords as you can for future use.


You have published a few posts and pages, so what do you do next? Share all your post on all major social media websites such as Facebook, Instagram, Youtube, and Pinterest.

Join all major groups, follow the biggest profiles, and don’t forget to take part in discussions as often as possible.

To rank your page on the first page of search engines, you shouldn’t forget to build links from other websites and use internal links.

Since links are an important ranking factor and each acquired backlink is viewed differently by Google, do not sleep on this.

Now, let’s see which plugins made our top list.

Our Top 5 favorite SEO Plugins for WordPress

1. Yoast SEO

[ embed video ]

PRICING: Free/Premium(from $104.50)
WP SCORE: 4.9 out of 5


  • Keyword optimization
  • Readability check
  • Redirect feature
  • Google Search Console integration
  • Automatic creation of XML sitemap
  • Excluding the “noindex” types of content from being indexed in search engine results
  • Title and meta description templates
  • Duplicate content detection
  • Regular updates
  • Open Graph data for sharing posts on social media

Yoast SEO is the most popular SEO tool for WordPress, and for a reason. It has over 5 million active installations and over 25.000 five star user reviews.

It comes as a free and premium version. While the premium option comes with extra things like redirect manager, internal link suggestions and block, content insights. The free option is great as well.

It is the complete SEO tool that helps websites to rank higher in search engines, and the Yoast team provides regular support on forums(Premium Users).

Anyone new or old to WordPress should at least give the free Yoast version a try.

2. Rank Math

[ embed video ]

PRICING: Free/Premium(coming in Fall 2020)
WP SCORE: 4.9 out of 5


  • Easy to follow Setup Wizard
  • User-Friendly Interface
  • Google Webmaster Central Integration(In progress)
  • Keyword Comparison & Google Trends Tool(TBA)
  • Google Crawl Errors
  • Contextual Help (tooltips, notices, help tabs, etc)
  • Image SEO
  • Schema rich snippets and article schema
  • News Sitemap for Submitting Websites on Google News(TBA)
  • Ping Search Engines
  • Manage meta tags such as noindex, noarchive and such

Rank Math is the new player in the SEO website optimization game and the fastest-growing as well. Some would argue that it’s also the most powerful.

This fantastic tool lets you optimize your website for search engines and social media. Unlike Yoast, Rank Math is still a free tool packed with premium options which otherwise, you would have to pay for.

The premium version is gonna be released very soon with more features that are announced on their official Facebook page. If you are still doubting whether you should switch from Yoast to Rank Math, don’t worry, you can do this easily by the 1-click migration wizard which comes integrated by default.

3. All-In-One SEO Pack

PRICING: Free/Premium(from $57)
WP SCORE: 4.7 out of 5


  • XML Sitemap support 
  • RSS Sitemap
  • Google AMP support
  • Google Analytics support
  • Markup
  • Support for SEO on Custom Post Types
  • ONLY free plugin to provide SEO Integration for e-Commerce sites, including WooCommerce
  • Nonce Security built into All in One SEO Pack
  • Generates META tags automatically
  • Built-in API so other plugins/themes can access and extend its functionality

If you don’t want to use Yoast or Rank Math, consider the All-in-One SEO Pack as your third option. As with the before-mentioned plugins, it also does the same thing, and it has a clean and user-friendly interface.

It offers a wide range of features, both free and paid tools to which help your website. One of the neat features this plugin offers is that you can use it to edit .htaccess file without FTP and edit your robots.txt file which is suited even for complete beginners.

As with Yoast and Rank Math, it also supports AMP (Google-friendly mobile version of your website). You can also optimize the WooCommerce store for SEO, and it’s packed with additional addons as well.

Clean, simple, and more affordable than Yoast. 

4. SEOPress

[ embed video ]

PRICING: Free/Premium for $39
WP SCORE: 4.9 out of 5


  • Redirections and 404 monitoring
  • Google Analytics stats in your WordPress dashboard
  • Video XML Sitemap
  • Titles & metas
  • XML sitemap
  • HTML sitemap
  • Backlinks from integration with Majestic
  • Keyword suggestions for your content via Google’s Suggestion tool
  • Google Structured Data Types: product, recipe, review, FAQ, course, article, event, local business, and video
  • Google Page Speed integration

SEOPress is a popular, fast, and simple SEO friendly plugin tool for website optimization. This is all thanks to its affordable price, clean interface that comes with a comprehensive set of features.

As with other SEO plugin tools in this list, expect to find open graph support, image, and content, XML sitemaps, meta title, and description features integrated within the plugin.

This means that you don’t have to slow down your website with other plugins that do one specific thing since SEOPress provides that in one affordable package. 

What differentiates this plugin from others in its price range is a unique feature of discovering new keywords via Google’s Suggestion tool.

5. SEO Framework

[ insert image from Slack ]

PRICING: Free/Premium(from $7)
WP SCORE: 4.9 out of 5


  • Duplicated content protection
  • XML Sitemap(Basic & Google News)
  • SEO Management for Robots direction, 301 redirects, and Canonical URLs
  • SMO manage­ment for Open Graph, oEmbed, RSS manage­ment
  • Includes structured data for breadcrumbs, corporate contact, blog posts, site links, search box
  • Automation for the title, robots, Facebook tags, Twitter card, and structured data generation
  • Google Search Console integration 
  • Bing webmasters tools 
  • Pinterest Analytics
  • Google AMP

SEO Framework is the only plugin on the list which claims to be a white hat SEO tool and it’s a great alternative to Yoast and Rank Math.

More lightweight than others and can intelligently generate critical SEO meta tags. This is achieved by reading a user’s WordPress environment in any language.

Design vise, the plugin is clean, simple, and looks like a part of WordPress. What it offers differently than others in the game is a colorful scale that shows you exactly what should you do next.

You can start with SEO Framework for free without any obstructive ads harassing you while you work. I would single out two fantastic features of this plugin and those are:

  • Uses a focus subject instead of a focus keyword, encouraging you to write more naturally 
  • Without any additional plugin, SEO Framework removes spam comments

Side-by-Side Comparison

Let’s do a quick rundown of all five Seo Plugins, compare their features, and see how they stack against each other. 

While Rank Math is completely free and has clear advantages against other plugins, keep in mind that a premium version is coming out in the coming months.

Yoast Rank Math All-In-One SEO Pack  SEOPress SEO Framework
Free Version Available Yes Yes Yes Yes Yes
Annual Pricing $39/site N/A $57/site $39/site $105/two sites
Rank Tracking Yes Yes Yes Yes Yes
On-Page Optimization Premium Yes No No No
XML Sitemap Yes Yes Premium Yes Yes
Customer Support Premium Yes Premium Yes Yes


SEO can get hard and confusing without the right tools. While using any of the mentioned tools is great on its own, here are some other options to accompany top SEO plugins for WordPress you should check out:

If we had to choose only one from all of these plugins, that would be Yoast in case you want a right-out-of-the-box simple and easy-to-use plugin. Otherwise, Rank Math is a tremendous option for those who like to fiddle around with extra features.

Either way, your website needs SEO optimization, so it’s best to just pick one tool and stick with it, as there is something for everyone on the list.

It is alright if you don’t become an SEO expert in one day, as these things take time. Try to take it easy and have fun.

Source link

What Automatic Plugin and Theme Updates Mean for Managed WordPress Hosting

As you may have heard, WordPress 5.5 introduces a User Interface (UI) for toggling automatic plugin and theme updates.

The underlying functionality has actually existed in WordPress since automatic core updates were introduced way back in WordPress 3.7, but for the first time WordPress core is shipping with a user interface for controlling what gets updated.

What Automatic WordPress Plugin and Theme Updates Look Like

As of WordPress 5.5, WP Admin contains a column in the plugins table and on individual themes’ detail screens enabling site administrators to enable (or disable) automatic updates.

Twice a day, WordPress will check to see if newer versions of your installed plugins and/or themes are available and, if you’ve opted into automatic updates, install the latest versions.

If any plugin or theme should fail to update, WordPress will revert that change and send an email to the site’s administrator.

Should I enable automatic WordPress plugin and theme updates?

The short answer, unfortunately, is “it depends.”

If you’ve worked with WordPress for a while, you’ve probably heard (or experienced) horror stories about plugin updates going awry: broken functionality, plugin incompatibilities, or even the dreaded “White Screen of Death” (WSoD) have occurred.

For a hobby site or personal blog, these may be a minor annoyance, but for stores running on platforms like WooCommerce, this can have a significant financial impact.

Ultimately, whether or not you enable automatic updates will come down to your risk tolerance and how much you trust the developers behind your favorite plugins and themes.

Note: For Hostdedi customers, you can rest assured that we’re taking daily backups of both your sites’ code and content. We also have visual regression testing to validate that the update went smoothly. If something goes wrong, we can have your site up and running again in short-order.

With that in mind, here are some tips to reduce the chances of an unattended plugin and/or theme update going off the rails:

Use single-purpose plugins from trusted developers

There are hundreds of thousands of WordPress plugins and themes available, but they are not all built the same.

Automattic, the company behind, maintains several of the most popular WordPress plugins: Jetpack, WooCommerce, Akismet, and more. They also have entire teams of developers and support technicians (“Happiness Engineers”) dedicated to the ongoing development of these plugins.

Likewise, companies like iThemes, Yoast, Sandhills Development, and Awesome Motive have built extremely popular plugins and products installed on millions of WordPress sites, but tend to run smaller teams that may be focused on multiple products concurrently.

Not all plugins have this same level of attention, though. In fact, many WordPress plugins are the result of a single developer scratching a particular itch and sharing their work with the world. The developer may not be interested in providing support, or may not have plans to update the plugin moving forward.

If you’re running a plugin that’s maintained by bigger names in the WordPress community, the chances of a plugin update completely breaking your site is likely far smaller than a small developer who may not have the bandwidth for handling support requests nor a solid QA process.

Your best bet is often to stick to plugins and themes from known entities. You might also consider incentivizing the developers of the plugins and themes you depend on; the plugin may have been free to install, but maintenance of a free plugin still takes time.

Similarly, try to avoid using plugins that try to do too much: the less an individual plugin is responsible for, the less likely it is to break in new and spectacular ways or have conflicts with other plugins.

Never modify plugins or themes directly

Sometimes a plugin does almost everything we want or a theme is almost perfect, and it can be tempting to tweak a value in the source and call it a day.

Unfortunately, the next time that plugin or theme gets updated, these changes are wiped away as WordPress replaces the entire plugin/theme directory with the newly-downloaded version.

A better approach is to extend the plugin or theme using actions and filters (collectively “hooks”) to make adjustments without touching the third-party code.

In the case of themes, we can further extend and/or override parts of the theme by creating a child theme.

Follow the development of critical plugins

If there are a handful of plugins that are crucial to your business, it may not be a bad idea to subscribe to any updates the developers might publish.

For instance, a WooCommerce store owner would likely benefit from subscribing to the WooCommerce Developer Blog — even if you’re not a developer, these blogs often hold details about the new features (and potential conflicts) in future releases.

Some of the larger communities (including WooCommerce) have dedicated Slack teams, where users can interface directly with the plugin developers.

Create (and Test!) Regular Backups

Sometimes, things will go wrong; whether an update goes awry, a site gets hacked, or an editor accidentally deletes a very important post, it’s always a good idea to have backups readily available.

For Hostdedi customers, you can rest assured that we’re taking daily backups of both your sites’ code and content. If something goes wrong, we can have your site up and running again in short-order.

If you want to have a second backup of your site (or first, if your host doesn’t offer backups), you may consider a plugin like UpdraftPlus or BlogVault, which let you schedule backups to external services.

It’s not enough just to create the backup, though; on a semi-regular basis, you should be restoring site backups to a development or staging environment to make sure everything you’re expecting to see is present. Don’t wait until you’re restoring a broken site to discover that some crucial data wasn’t included in your archives!

Automate the Testing of Updates

There’s a big movement towards automation these days, and you can take advantage of these tools and techniques to make sure your sites are always behaving as you expect.

For example, you might use a service like Reflect to write a series of automated tests for your site. Specify key URLs, tell the service where to click and what to look for, and instruct it to run the tests every few hours. Should the tests ever fail, you’ll get an email alerting you to the fact that something has gone wrong.

Of course, if you’re running tests every 12 hours but plugin updates are happening somewhere between those intervals, you may find that your site is broken for hours before you even know about it!

This is where your web host comes in: if you’re on any sort of Managed WordPress hosting plan, your host should be proactive in letting you know if updates are breaking your site.

For example: at Hostdedi, we don’t simply apply every plugin update as it becomes available. Instead, we perform what’s known as Visual Regression Testing before each and every plugin update. Here’s how it works:

First, we determine a set of important, representative URLs on a site: the homepage, shopping carts, product catalogs, blog posts, etc.

Next, we create a copy of your site within our network, and take screenshots of these key URLs; these serve as the “before” snapshots.

Once we have a set of screenshots, we upgrade the plugin on the cloned site, then take fresh screenshots of those same URLs to get our “after” images.

Finally, with both before and after screenshots in-hand, we compare these images to see if anything has changed on any of the pages and/or if any errors have popped up; if nothing has changed, we go ahead and upgrade the plugin on the production site. If however we do detect differences, we alert you (and show our work) so you can decide whether or not to upgrade the plugin in question.

What’s the point of Managed WordPress hosting if I have automatic updates?

Whether you opt for WordPress’ native automatic updates or the more sophisticated offerings included in your Hostdedi Managed WordPress/WooCommerce hosting, keeping your site performant, secure, and online extends beyond just keeping things up-to-date.

Every day, we’re tweaking configurations and building new features to squeeze every bit of performance out of our platforms, built by people who know WordPress inside and out. From auto-scaling to Content Delivery Networks (CDNs), our platform is designed from the ground-up for speed, security, and ease of use. At the same time, we’re partnering with industry leaders to deliver the best of the WordPress community for a low, monthly price and backing it all up with best-in-class, 24/7 support.

Whether you opt to use WordPress core’s automatic updates or trust us to handle them for you, know that Hostdedi is there for you every step of the way.

Source link

Use WordPress Testing Tools to Build Your Plugin & Run Unit Tests in Github Actions

We’ve been talking a bunch about unit tests lately, starting with the basics, and then moving up to adding tests to a plugin, so you could see it in practice. We’ve also covered how to use Github Actions to deploy your site automatically to your host. Today, we’re going to take pieces from both of these concepts and combine them, so that we’re running our tests automatically with Github actions when we push new code to the repository.

The easiest way I’ve found to get started is with WP Testing Tools from Valu Digital. The team at Valu Digital has provided a fairly easy way to get your tests up and running on Github Actions. We’re only going to cover how to use their base template to start from scratch with your plugin development so that you can run tests. Adding their test setup to an existing plugin takes a bit more work.

Add WP Testing Tools Setup to an Existing Plugin

To start, clone the repository onto your local computer. your-plugin-name

Next, we need to grab the plugins folder from inside the repository as that will be the base for our plugin. Migrate that folder to where you want your new plugin and rename it to match the plugin name you want to use. 

Dealing with Composer

This testing setup requires Composer, which you don’t need to be intimately familiar with today. I’ll cover Composer in detail in a future post. For now, you’ll need to run composer install to install the required dependencies for WP Testing Tools.

Unfortunately, I’ve found that the repository is missing some required Composer packages so we’ll need to make sure these are also installed with the following commands.

composer require codeception/module-rest --dev 

composer require codeception/module-phpbrowser --dev

composer require codeception/module-db --dev

composer require codeception/module-asserts --dev

composer install

Wait, I got memory errors with Composer. Help! It probably doesn’t matter and you shouldn’t get them in Github Actions so you can ignore it for now.

Now we have the proper tools installed, you can push to Github and you’ll see that the unit tests run without issue. This plugin still isn’t ready for us to build on though so let’s get to renaming the other strings in it and make it our own.

Setting Up Plugin Files

We can start by renaming the plugin header information found in plugin.php. Name it whatever suits your plugin and make the author yourself. We’ll also need to change the namespace and class entries so that we’ve named them properly for our project. I’m changing the namespace to my company name and using PluginBase as my class name for this tutorial. You can see my working renamed file below. I’ve also cleaned up the comments to make it easier to read.



 * Plugin Name: Hostdedi - Github Actions Unit Tests

 * Plugin URI:

 * Description: Plugin base that runs unit tests with Github Actions

 * Author: Curtis McHale

 * Version: 0.1.0


 * @package example


 if (!class_exists('SfndesignPluginBase')) {

    require_once __DIR__ . '/vendor/autoload.php';



Now in composer.json, we have a few things to change around as well. Make sure that you’re listed as the author of the plugin and change the links to Github Issues and Source to match your repository. You’ll also need to change the namespace of your plugin under the autoload entry. I’m using my company name so mine says Sfndesign. You can see my changed composer.json file below.


  "name": "sfndesign/pluginbase",

  "description": "Actions Plugin",

  "type": "wordpress-plugin",

  "license": "GPL-2.0-or-later",

  "authors": [


      "name": "Curtis McHale",

      "email": "",

      "role": "developer"



  "require-dev": {

    "valu/wp-testing-tools": "^0.4.0",

    "lucatume/wp-browser": "~2.2",

    "codeception/module-rest": "^1.2",

    "codeception/module-phpbrowser": "^1.0",

    "codeception/module-db": "^1.0",

    "codeception/module-asserts": "^1.3"


  "autoload": {

    "psr-4": {

      "Sfndesign\": "src/"



  "scripts": {

    "wp-install": "wp-install --full --env-file .env --wp-composer-file composer.wp-install.json",

    "wpunit": "codecept run wpunit",

    "functional": "codecept run functional",

    "test": [





  "config": {

    "optimize-autoloader": true


  "support": {

    "issues": "",

    "source": ""



Now we need to change the name of the Example.php file found in the src directory. I’m going to call it PluginBase.php to stick with the format we’ve been using. Next, open that file and change the namespace to Sfndesign and the class name to PluginBase. You can see the adjusted file below.


namespace Sfndesign;

class PluginBase {

    public static function init() {

        define( 'EXAMPLE', 'initialized' );

        add_action('the_title', function () {

            return 'EXAMPLE TITLE MOD';




Now that we’ve made these adjustments we need to run composer update again so that Composer registers the new autoload paths that are needed with our renamed files.

Finally, to make sure the whole thing is working well, I find it easier to change their initial test found in tests/ExampleTest.php to something that will return true no matter what. You can see this code below.

 public function testInit()




Now that we’re set up, you can initialize your plugin as a git repository and then push it to Github. Once you’ve done this you should see an action running under the Actions tab for your repository and everything will come back green because your unit test has been run.

Throughout the last few posts, we’ve written tests and used Github Actions to automate parts of our process. Now, it’s up to you to use these tools in your client projects. You won’t write tests later, so make sure you start your projects with tests from the beginning. If you want to go even deeper with testing there is an excellent course by Fränk Klein that explains Unit Testing in WordPress. It’s already on my list to go over so that I can get better at my testing practices.

Source link

What is the Best Contact Form Plugin for WordPress?

Contact forms are needed on almost all websites. Luckily, there are a number of easy-to-use WordPress form plugins on the market.

A contact form is a way to gain feedback from customers or allow them to contact you directly through your site. The most commonly used form plugins all have a pretty similar set of features and integrations. 

  • Allows you to view form entries
  • Works with a captcha service
  • Works with Zapier
  • Works with Mailchimp and other marketing services

The marketplace has shifted a fair bit from the contact form options that used to be available for free and feature complete form plugin options. There are now so many solid options to pick from that choosing a contact form plugin for your site all comes down to which one you prefer and how well it works for you. 

Ask yourself these questions to work out which form plugin solution is the right one for you.

  • Do I need the paid version of this plugin or will the free version work? 
  • Will I need more add-on and features for my forms down the line?

Caldera Forms

Caldera Forms is a solid, free form plugin that has more options than most. Caldera Forms is developed by Saturday Drive, the same company behind Ninja Forms. Caldera Forms has an easy to use drag-drop interface for building forms. You could use Caldera Forms for building a simple contact form, a simple booking form, a credit card payment form, or a rating form.

  • One of the best free form plugins
  • It contains all of the features you will need
  • Easy to use

Everest Forms

Everest Forms plugin has a complete set of features and is another option worth checking out on your site. WPEverest is the company behind Everest Forms.

  • Drap and drop
  • Clean UI
  • Easy to use


Forminator is a pretty new form plugin from WPMU DEV. It offers a very complete set of features in the free version. 

  • Drag and drop form blocks
  • Complete set of integrations with common services
  • Includes a block for the block editor
  • Email routing
  • Front-end post submissions
  • Multi-fie upload field

The only feature that is not in the free version of the Forminator plugin is the e-signature feature which offered in the Pro version. Forminator is worth checking out.

  • Feature complete
  • Is not a limited form plugin
  • Solid for a free plugin


weForms is another solid plugin that comes with a huge range of features built-in. BoldGrid is the company behind weForms. If you are using the block editor then weForms comes with a block.

  • It just works
  • Easy UI
  • Has a number of built-in features


The MetForm plugin works with Elementor which means that you can control the form from within the Elementor page builder on your site. Wpmet is the company behind MetForm.

  • Clean UI
  • Works in Elementor which means you can edit forms in Elementor
  • Has a number of integrations built-in

Contact Coldform

One the easiest to use simple form plugin options for a contact form is Contact Coldform. Jeff Star is the plugin developer behind the Contact Coldform plugin.

  • Easy to use
  • Works well
  • Basic and does exactly what it says

Gutenberg Forms

If you are using the block editor on your site then one of the recommended form plugin for the block editor is Gutenberg Forms.

  • Works with the block editor
  • Native in the block editor
  • Easy of use

Contact Forms by Gutenforms

If you are using the block editor on your site then another recommended form plugin for the block editor is Contact Forms by Gutenforms.

  • Simple forms
  • Block editor compatible
  • Simple to use

Honorable mentions for more well-known form plugins for WordPress include Gravity Forms, Ninja Forms, and Formidable Forms. Ninja Forms and Formidable forms both have versions which are on Gravity Forms is a premium form plugin which comes with many features and add-on plugins for extra features and integrations. Ninja Forms and Formidable Forms also come with add-on features and all have pretty similar levels of features and add-ons, and well-priced plans.

Please take the time to test drive any of the contact form plugins we’ve mentioned on your staging site. After you have tested the form plugin of your choice, you can now begin creating all of the needed forms on your site.

Source link

Git Hooks – Hostdedi Blog

Git is a powerful version control system that we’ve barely scratched the surface on over our last few posts. Today, we’re going to look at the automation power that Git can give you with Git Hooks.

Every repository gets hooks built in when you use the git init command. When a repository is initialized you get a hidden .git directory and inside that is a directory called hooks that will contain all your hooks. Open any git repository you have handy and use ls -a to see the hidden directory, then open it up in your favorite code editor.

To start you’ll see a bunch of files with .sample file extensions. These are exactly what they say, sample scripts that you could use in your projects. The files are named to correspond with the hook they run on. So post-commit.sample runs on the post-commit hook.

You can use pretty much any language to write a hook. The file is parsed according to the shebang notation at the top of the file. If you wanted to use node you’d use #! /usr/bindi/env node and your file will be parsed as a node file.

Before we dive into what you can do with git hooks, let’s take a look at some of the hooks that are available to you.

Types of Git Hooks

Commit Workflow Hooks

pre-commit is run before you even enter your commit message and it can be bypassed with git commit --no-verify.

prepare-commit-msg can be used to edit the default message you see in your commit message. Use it to give instructions to developers about what type of commit message they should be leaving. It can also be used to automate the contents of where the message is automatically generated for you, like merges or to add an issue number to your commit message automatically.

commit-msg can be used to validate the commit message for your project. Maybe you don’t want anyone to be able to put in a commit message that simply says “dealing with white space”. You can use this hook to detect the presence of the words white space and then exit and provide a warning to the user that they need to have a better commit message.

post-commit runs after all the commit hooks above. It’s most useful for a notification that a commit has been made.

Client Hooks

post-checkout runs after you’ve run a successful git checkout command. If you had a set of large files used on the site but didn’t want them in source control, you could use this command to move the files for you.

pre-push runs during a git push command before any objects are transferred to the remote repository.

Server Hooks

pre-receive runs when a client has pushed code to a remote repository. This can be used to check the code that is being pushed to make sure that it meets the criteria of your project before you accept the push.

post-receive runs after your remote repository has received the updates. This could be used to call a web hook which triggers a deployment process or notifying a chat room that a commit has been received and is ready for review.

Many of the hooks above can be set to run only on specific branches. That may mean when you use a post-receive hook only when someone has pushed code to the main branch that’s supposed to be ready to deploy. A list of developers could be notified to review the code and then deploy it. This way you would always have 2 sets of eyes on a deploy which can mean catching mistakes that a single developer can easily miss.

I’ve skipped some of the hooks that are available because I’ve never seen a need to use them. One set of hooks I didn’t talk about is the email workflow hooks. If you’re not accepting patches to your code via email, then you’ll likely never need them. You can find all the available hooks in the documentation.

In practice hooks I’ve used most are:

  • pre-commit
  • pre-push
  • commit-msg
  • pre-receive
  • post-commit
  • post-receive

Now let’s do something with these hooks.

Activating a WordPress Plugin with WP Cli and Git Hooks

For one client project this year I was adding a store, and still doing a few tasks on the main site. That meant the main site did not have any of our WooCommerce plugins installed or activated. I needed to develop the WooCommerce store on one branch and only once I was ready to push it all live, did I want to move WooCommerce over to main.

To start we’ll need a new branch called store. We can get this by using git checkout -b store. This creates a new branch and checks it out for us. Now let’s get the hook ready.

First we need to create the post-checkout hook with this command touch .git/hooks/post-checkout.

Next we need to make it executable. We can do this with the chmod command from terminal chmod +x .git/hooks/post-checkout.

Now open the file in your code editor of choice and copy the code below into your post-checkout file.

#! /bin/bash

wp plugin activate woocommerce

echo "activated WooCommerce"

wp plugin activate automatewoo

echo "activated AutomateWoo"

You can demo this by changing to any branch via terminal. You should see two lines telling you that WooCommerce and AutomateWoo have been activated. We know it’s working, but it’s not quite what we want because it will turn the plugins on every single time we change to any branch.

What we really want is to turn them on when we move to our store branch, and then turn them off when we are on our main branch. To do that we’ll need the hook to detect which branch we are one. Swap the contents of post-checkout with the code below.

#! /bin/bash


branch_name="(git symbolic-ref HEAD 2>/dev/null)"

if [ "refs/head/store" = "$branch_name" ];then
  wp plugin activate woocommerce
 echo "activated Woo"

  wp plugin activate automatewoo
 echo "activated AutomateWoo"

if [ "refs/head/main" = "$branch_name" ];then
 wp plugin deactivate woocommerce
  echo "deactivated Woo"

  wp plugin deactivate automatewoo
  echo "deactivated AutomateWoo"

This code starts by assigning the branch we are checking out to the branch_name variable. Then we have two if statements. The first checks to see if we have moved to the store branch. If we have it uses WP CLI to activate WooCommerce and AutomateWoo.

The next if statement checks to see if we are on the main branch. If we are, it will deactivate the plugins with WP CLI and tell us about it in the terminal.

Controlling Git Workflows with Git Hooks

In a previous post on Git I talked about different Git workflows. One very common use case for hooks is to stop anyone from committing code directly to the main branch. You can use a hook to make sure that all code is merged from a different branch into main.

Start by renaming pre-commit.sample to pre-commit and then make it executable as I’ve described above. Next grab the code below and use it in the pre-commit file.

#! /bin/bash

branch="$(git symbolic-ref HEAD 2>/dev/null)"

if [ "$branch" = "refs/heads/main" ]; then
echo "WHOA that was '"${branch}"' you should not do that. Stop doing silly stuff and create your own branch and merge it."
exit 1 # if you remove this it won't block the commit but it will send the message to slack


This checks to see if we’re on the main branch, and if we are, the commit is stopped. Then it prints a reminder to the user that they shouldn’t be committing directly to the main branch.

Remember many places are changing to main as their branch. Older projects may need master in place here if they haven’t updated.

You could even take this a step further and use cURL to access the API of a chat app and then complain publicly that someone tried to commit to main.

The only limitations of git hooks are your imagination. You could use them to stop someone from committing if a TODO is present in their code or to stop whitespace at the end of a file.

If you have some part of your workflow that is a continual stumbling block, look at hooks to automate it, so that you don’t have to remember.

Source link

Understanding WordPress Unit Testing Jargon

In our last post, we took a basic look at testing your code in WordPress. Today, we’re going to take another step towards writing well-tested code, by introducing you to (and helping you understand) all the jargon that gets thrown around when you talk about unit testing for WordPress.

Types of Tests

Yup, unit tests are not the only types of tests we can have for our application so let’s look at the different types of tests you may use in your work.

Unit Tests

These types of tests are the first stage in a testing system. They specifically test to ensure that the code you wrote performs as expected. Unit tests form the foundation of your tests because if your code doesn’t work properly, then later types of tests are built on a shaky foundation.

If I wanted to limit the editing of permalinks to site administrators for posts that are over two weeks old my unit test would use WP_Mock to ensure that I have a user of the proper type and a post with the proper date. Then I’d make sure that my function returned the expected true or false value.

Unit tests should have no dependencies outside of the code you’ve written. They should interact with no other system. That means our last post wasn’t a true unit test, it was an integration test because we interacted with the database as we created our user.

When you use unit tests as the foundation of your work, you help ensure that each method/function has a single responsibility because it gets progressively harder to test as you add more conditions to a single function.

Some of the tools you’ll encounter in unit testing WordPress projects are:

Integration Tests

This is the second type of testing you’ll do in your work. Integration tests make sure that the interactions between two systems function as expected. Unlike unit tests, the goal here is to see the interaction between multiple systems.

WordPress itself does more integration tests than unit tests because when most of the application was written best practices were different. The functions inside WordPress are much larger than many newer PHP CMS’s and do much more work. These bigger functions are hard to unit test properly because they do so much. That means we rely more on integration testing as we check how our code directly works with WordPress.

None of this is bad, it’s simply a product of an application that wasn’t built when testing was as common as it is now.

Another example of an integration test would be if you were building an integration with an email marketing platform. You may use unit tests to make sure you validate the email properly, and submit the form as expected. Integration tests would be used to ensure that when you submit your valid email to the email platform you deal with the response properly.

Tools for integration testing:

Mutation Testing

Mutation testing is only going to be used for projects that have some sort of test coverage already. This type of testing creates “mutants” of your code by introducing common coding errors. The goal is that your unit tests break when these errors are introduced which means you’ve caught and killed the mutant. Mutation testing tools will report back on how many mutants you’ve killed and the places in which you haven’t caught mutants.

Mutation testing can be used to measure the quality of your test coverage. If you’ve got lots of mutants alongside 100% testing coverage, you have a big problem. This means that your tests don’t catch common errors programmers make. You’ve got code breakage waiting to happen.

Essentially, you’re testing your tests.

Tools for mutation testing:

Acceptance Tests

These can also be called functional test or browser testing. Where unit tests start with your code and work outwards, acceptance tests take the view of the person using your software. With acceptance tests, you may automate the web browser to interact with your site to make sure that users see what they expect to see.

Acceptance tests are harder to maintain because a small wording change in the UI of your software can mean that the test breaks because the automation can no longer find the UI elements it expects to find. For that reason, only invest in acceptance tests for business-critical infrastructure, like the checkout process on your shopping cart.

Tools for acceptance testing:


Now that we’ve covered the types of tests you can do, we need to make sure we understand the other language that developers will use as they write tests.

Test Doubles

The term test doubles is a generic term that refers to any time you replace a production object/function/thing for testing purposes. We did this in our previous post on Getting Started with Unit Testing in WordPress when we used WP_UnitTestCase to add a user that didn’t exist in our production database. It can be helpful to think of it like a stunt double who “stands in” for the actor when things get dangerous. Test doubles “stand-in” for our data and code to make testing easier. They should look and behave like their production counterparts but be simplified to reduce complexity when we’re testing.


Mocks are used when you don’t want to interact with the API or database. You use a mock to fake database interactions so you can test a single unit of code without adding the complexity of a database.

A mock doesn’t have to be data in a database. A tool like WP_Mock has the ability to fake the hook system inside WordPress. This lets you test to see if a hook was called in your function, without needing to interact with WordPress itself.

Below we can see an example in WP_Mock where we fake the get_permalink function. We provide the number of times we expect the function to be called, arguments we expect, and the value we expect returned.

WPMock::userFunction( 'getpermalink', array(

  'args' => 42,

  'times' => 1,

  'return' => 'https://theanswertoeverything.fourtytwo/guide

We’ll cover how to use WP_Mock in a future post.


Stubs are hard coded values for our tests, like canned answers to the questions our test may ask. You would be using a stub if you instructed your test to assume that a user is logged in while running a test. Another test may assume that the user is logged out. Both tests would be making sure that your functions returned the proper values for the given branch in your code.

It’s very likely that you’re using stubs and mocks together. In the example above, you use a stub to assume the logged in value, and then a mock to make sure that the proper values are returned.


Test dummies are used when you don’t care about what the code does. Maybe you use a dummy to fill in an array or parameter list so that the code works properly. Stubs are extra information that likely doesn’t matter in the context of the specific test you’re writing.

For a logged-in user, maybe part of the function your testing expects a name. Even if your current test doesn’t need that name, you need to make sure it’s filled in so that your test passes. Of course, you should also test the result of your function without that name so you’re sure that you handle failure conditions properly.


A factory is a tool that lets us populate valid objects in our data model so that we can test the data. In our last case we used a factory when we added a user to our code inside WP_UnitTestCase.

One thing to be wary of here is changing the data model in your code. If your user suddenly needs an extra field, then you’ll need to head into every test and make sure that you have added that extra field every time you’ve used a factory.

Monkey Patch

This is a catch-all term for dynamically replacing attributes and functions at runtime. WP_Mock is “monkey patching” by replacing the default WordPress functions for testing. This means that we don’t have to call into WordPress directly when we’re unit testing.


An assertion is a boolean value which will be true unless there is an error. An example would be using assertFileEquals to check if a file has the expected content. It will return true if the file matches expectations, and you have a passing test.


Now, what overall system are you going to approach your tests with? Does it matter more that individual functions are valid, or that the behavior the end-user sees is valid?


TDD or Test Driven Development is when you write tests to validate that the code functions as expected. Like unit tests, you’re starting with the expectation of the code and then working towards the customer/user as you go. TDD doesn’t care about the outputs, it’s only concerned that the tests function as expected.

Tests written under TDD are only going to be readable by developers that understand testing and what an assertion means.


BDD or Behavior Driven Development grew out of the shortcomings of TDD. Here you start with what the end-user expects to happen as a result of the code. You still write your tests first, but you focus them on the result of your code. BDD doesn’t care how you arrive at outputs, as long as the expected behavior is the result.

One big benefit to BDD tools like Cucumber is that the language used to write the test is easily readable by customers and developers. It’s easy enough to understand that customers can write feature requests using Cucumber after a brief introduction.

Now, which one should you use? The correct answer is probably a bit of both. TDD methods can be used to ensure that the code the developer writes runs as expected. BDD can be used to make sure that the output of that code is what the customer expects to happen.

That’s all, folks! Understanding unit testing for WordPress just got a lot easier. With all that jargon under your belt, you’ll be ready for the next post where we’ll build a plugin using TDD and BDD with all the tools at our disposal.

Source link