How to Improve Organic CTR (Click-throught Rate) in WordPress

How to Improve Organic CTR (Click-throught Rate) in WordPress

Search engines remain one of the most important traffic sources for websites. Learning to improve organic CTR (click-through rate) is crucial for taking advantage of them.

When it comes to SEO, many website owners simply focus on ranking. They think that as long as they make it to the first page of Google, traffic will sort itself out.

However, achieving a high rank in the SERPs doesn’t help you if nobody ends up clicking on your content. In that case, your search rank is nothing more but a vanity metric.

Plus, CTR and search rankings are intimately connected. If you check all the boxes on Google’s relevancy radar but can’t move real people to check out your stuff, the search engine will happily demote you.

Conversely, working on your click-through rate is a good way of improving your search rank. In fact, data suggests that improving organic CTR by 3 percent will move your site up one spot in the SERPs. It’s another great way to increase traffic without creating new content.

So, how do you do it? That’s what this post is about.

How to Improve Organic CTR for Your WordPress Website

In the following, we will go over actionable tips to increase the click-through rate of your site.

First Things First, Check Your Current CTR

Before going about trying to make the situation better, it’s a good idea to learn about the status quo. Luckily, as website owners, we have powerful tools for that at hand.

The first stop when trying to improve organic CTR is Google Analytics. Here, go to Acquisition > Search Console > Queries. This screen shows you which search queries bring people to your site.

It also displays the queries’ clicks, impressions, click-through rate, and average search position. Further information is available in the Landing Pages menu. Here, you learn similar data about the different pages on your site.

how to improve organic ctr landing pages in google analytics

Between those two, you should easily be able to figure out which of your content performs well and which doesn’t. From there, you can take targeted action to improve organic CTR for the pages and keywords that don’t measure up. We will get to how to achieve this soon.

Afterward, you can use the same tool to see if your efforts have any effect by comparing the time before and after you have made changes.

compare ctr in google analytics

Pro tip: I personally find it easier to do the comparison within the actual Google Search Console (don’t forget to check out our guide). Once there, look under Search Analytics to find the same data and ability to compare.

compare ctr in google search console

Alright, now let’s look at some actual measures.

Improve Your Titles

The page title is the most prominent part of your search results.

serp snippet

For that reason, a lot of your focus should be on making it as effective as possible. Here are a few pointers on how to do that:

  • Try out many different headlines — The first step to creating great headlines is to give yourself options. Don’t go with the first thing that pops into your head but try to come up with several alternatives. Jon Morrow famously wrote 100 headlines per day in his beginnings at Copyblogger. While you don’t have to go to these lengths, maybe try to come up with ten alternative headlines for a post and see how it improves the quality of its title.
  • Focus on emotions — Most decisions are motivated by feelings, including clicks. For that reason, a good way to get people to check out your content is to shift your headline focus from keyword centric to being centered on emotions. Find more details in our copywriting tips.
  • Use Listicles — List posts are proven to boost CTR. People love them so much that some websites seem to live off of top-X lists alone (I am looking at you BuzzFeed). Listicles offer information in an easily digestible form so don’t hesitate to employ them. Pro tip: when you do create a list post, shoot for even numbers. Top 10, 20 and 30 lists work better than numbers like 7, 16 or 23. Also, the sweet spot appears to be around 10-20 items per list.
  • Use Proper Formatting —Appearance matters, including for blog posts titles. For example, if they appear cut off in the SERPs, they are much less appealing to click on. Yoast SEO and All-in-One SEO Pack are both great tools to preview what your content will look like in search engines. Plus, each of them you set up sitewide title structures as well as custom titles per page and post.

Thoroughly Test Your Headlines

However, you don’t have to rely on guesswork to improve your content titles. Instead, you can get proof for which title is going to perform well. There are several ways to do so:

  • Use the right tools — The Internet offers a number of tools that will check your headlines for different factors of success. Good examples are the CoSchedule Headline Analyzer and the Emotional Marketing Value Headline Analyzer by AMI.
  • Test titles on social media — On social media it is common to post the same content several times with different titles. They also offer objective data on which performs the best. An excellent opportunity to put your ideas titles to the test. Tools like Buffer have built-in functionality to help you.
  • Use PPC ads for testing — If you have money to spare, you can also test headlines with online ads. Simply buy ads for the page you want to improve organic CTR for and use them to try out different titles. Let the ads run until you see a significant trend and stick with the winner. Facebook advertisement works, too.
  • Use a WordPress plugin — WordPress also has tools for A/B testing. Title Experiments Free lets you set several headlines for your blog posts that get served up to visitors randomly. Depending on what gets clicked the most, you can then choose the right version. Repeat as necessary.

Make Your URLs Descriptive

The next part of what people see in the SERPs is your content’s URL. It is one of the places where you can and should place keywords (learn more about on-page SEO here).

This is an important signal for Google, however, it also matters to potential human visitors. Microsoft has found that descriptive URLs perform 25 percent better than generic ones.

25 percent! That’s a quarter of additional traffic you are potentially missing out on.

Besides keywords, you can further improve your URLs by using categories and sub-categories in your link structure. This puts search results in a wider context and lets visitors know that there is more than this one article or product in the area they are interested in.

how to improve organic ctr descriptive urls

Plus, you can easily set it up on your WordPress site under Settings > Permalinks.

adjust wordpress permalinks

Double Down on Meta Descriptions

Next up in the search snippets are meta descriptions. For the uninitiated, that’s the text that appears under the result title and link.

In the meta descriptions, you can tell potential visitors more about what to expect from your content. It also makes up the majority of the search result.

The first rule to improve organic CTR via meta descriptions is to make sure you even set a custom description for each post. If you don’t, Google will simply pull any sentence that contains the search keyword, which often makes less sense. Plus, you can use the aforementioned SEO plugins to achieve this.

how to improve organic ctr set custom meta description

One way to make meta descriptions more effective is to use power words. These are phrases and words that appeal to the emotional part of the brain. This doesn’t just apply to meta descriptions but your content in general. Smart Blogger has a detailed list that you can feel free to steal from.

Aside from that, again, also concentrate on appearance. Avoid making meta descriptions too long so that they are cut off. More tips on how to write great meta descriptions here.

Set up Structured Data

Have you ever seen a search result like this?

rich snippets

If so, you already know what structured data. It is used to create rich snippets that contain additional information for web content like ratings, images, preparation time (for recipes) or even breadcrumb navigation. These can increase organic CTR by 30 percent!

In addition to that, Google increasingly uses structured data to display information right in the results page, often before the organic search results.

how to improve organic ctr structured data rich snippets

This development will likely continue in the future. To take advantage of it, it’s crucial that you implement structured data on your WordPress website. Lucky for you, we have a detailed article on this very topic right here.

Improve Site Speed

The final ingredient to ramp up your organic click-through rate is making sure your site loads as fast as possible. After all, a click only counts if the visitor actually lands on your page. Should your site loading speed be too sluggish, this might not even happen, especially on mobile devices that often have slower Internet connections. Plus, Google search rank is directly correlated with loading speed.

google rank and ctr

Consequently, investing in site speed is an important factor if you want to improve organic CTR for your WordPress website. Luckily, there are plenty of things you can do and find a lot of input in this article as well as this post. Aside from that, you’d do well to invest in other ways to make your site mobile friendly.

How Will You Improve Your Site’s Organic CTR?

Organic click-through rate is an important, yet often underestimated factor for the success of a website. You can produce solid content, however, if nobody clicks on it, it will flounder in the search results.

Thankfully though, you have a lot of control in the matter and there is a lot you can do to improve your organic CTR. In this article, we have gone over a number of ways to do so. Let’s summarize them one more time:

  1. Track the current state of your click-through rate
  2. Focus on improving page titles
  3. Test page titles in order to pick the most effective
  4. Improve URL structure to make it descriptive
  5. Pay attention to your meta descriptions
  6. Make use of rich snippets and structured data
  7. Make page loading speed a priority

Once visitors click through to your site, it’s also important that you learn how to keep them around. As usual, organic CTR is only one piece of a larger puzzle for the success of your website. However, it is one that you are now prepared to tackle.

Do you have additional tips on how to improve organic CTR in WordPress? If so, please share 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 How to Improve Organic CTR (Click-throught Rate) in WordPress appeared first on Torque.

Read Full Article Here

Advanced OOP For WordPress Part 6: Continuous Integration For WordPress Plugins

Advanced OOP For WordPress Part 6: Continuous Integration For WordPress Plugins

This article is a part of a series on writing object-oriented PHP for WordPress development. So far, we’ve spent two articles on writing the code and now we will test the code and systems. It takes an enormous amount of tooling to write code and back in my day I walked uphill both ways, in two feet of snow, to write HTML, using HTML instead of writing it in Babel and transferring it to HTML.

Yes, it’s a lot, but that’s why we have scaffolding tools, and we’re going to get into some of those in this article.

Object-oriented programming (OOP) is complex. The point of this series is to show why creating abstract systems to do things is sometimes better than writing a system to do one thing. When that is true, OOP is worth the additional complexity. One key benefit of OOP is that testable code, tends to be better code.

Since OOP code is highly testable, it’s reasonable to adopt a workflow where all code is automatically tested. Passing tests becomes a requirement for merging pull requests. Github and GitLab can enforce this rule on pull requests. This is an important component of the workflow if you want to adopt test-driven design (TDD,) which this series will switch to soon.

In this article, I’ll be showing you how to use Github and Travis CI to automatically run the tests that I showed you how to write in the previous articles.

Git Flow And Testing

The Git Flow Workflow is a very common choice for collaborative development using Git. When using this workflow, no one ever commits directly to the branch currently being developed on. Instead, all work happens in branches, and a pull request on Github is used to review and then commit the changes back to the main branch.

For example, if you were tasked with implementing features specified in issue 42 in a branch called “develop”. In this case, you would pull the remote git branch develop. Then create a local branch off of develop. That branch would be called feature/42, since it is introducing a feature from issue 42, and then push that feature back to Github. A pull request to merge feature/42.

Setting Up Testing Automation With Travis CI

Travis CI is a free service that integrates with Github pretty seamlessly. Once you’ve signed up for a Travis CI account, you can connect your personal repos and organization repos. Then in the Travis CI profile for your personal account or organization, search for the repository you want to enable Travis for and activate it.

This takes you to the Travis page for your repo. Go to settings and set Travis to run on all pull requests.

Keep that screen open. We’ll need it once we are ready to use Travis, but that requires a Travis configuration file — .travis.yml.

This is the configuration file for the Travis build environment, which is running inside of a Docker image. You can use this file to configure that environment — for example we’ll tell it we want PHP available. You can use this file to run scripts in that environment, for example the bash and composer scripts I showed how to create in previous articles in this series.

Let’s start with a basic Travis file that just runs our unit tests.

# Do not give sudo access
sudo: false

# Use the PHP environment
language: php

# Don't send notifications via email, that's annoying
    on_success: never
    on_failure: never

# Trigger only on master -- we'll add Github pull requests in settings
    - master

# Cache composer dependencies
    - vendor
    - $HOME/.composer/cache

# Build these combinations of PHP and WordPress Versions
    - php: 7.2
      env: WP_VERSION=latest
    - php: 7.1
      env: WP_VERSION=latest
    - php: 7.2
      env: WP_VERSION=trunk

# Setup environment
  # Export composer
  - export PATH="$HOME/.composer/vendor/bin:$PATH"
  # Install plugin with composer
  - composer install --no-progress
# Run tests
  # Run just unit tests
  - composer unit-tests

Travis Life Cycle Events

This file has inline explanations. I want to highlight a few parts that are very important concepts. First, the matrix. Because this matrix includes three combinations of PHP and WordPress versions, Travis will perform three builds each time. Each run will use the PHP version specified and will have a different value for the environment variable WP_VERSION. The bash scripts that I created — based on Gutenberg — all set the WordPress version they are using the environment variable WP_VERSION. It’s a convention that we should stick to.

Next look at “below_script”. This is a lifecycle event that Travis exposes. This event runs before the script event, which is normally where the test script runs. At this stage our travis file setups up composer and then uses it to install the plugin’s dependencies. This has to happen before the tests are run or they will fail for the wrong reason — bad install, not bad code.

Then we have the “script” event. By default, in a PHP project, Travis will execute the command “phpunit” here. We want to run a slightly different command. More specifically the command “composer unit-tests”. That’s the Composer script that encapsulates running unit tests.

In the next series of this article, we’ll use Travis lifecycle events to run code sniffs and lints before the tests. Then, with one build, we’ll create a code coverage report, that can tell us what percentage of our code is covered by our tests.

Testing The Travis Configuration

Now commit this file and push it to Github, in the master branch. Then go back to the Travis settings screen and from the “More Options” menu, use the “Trigger Build” to trigger a build. That should cause the build process to run and once it’s done, you’ll see the status.

If you had a resolvable set of dependencies that are all passing tests, you should see each three build passed. You probably didn’t. Travis is a much less forgiving environment than most of us use for local development. That’s a good thing. If everything works in Travis, then it likely works elsewhere. Read your error logs and work through each one until you’ve got passing builds.

The complete configuration with Docker I’m about to show you how to build, when I set it up for the example plugin took me twelve tries to get it right. I’m borrowing liberally from Gutenberg and I’ve done this before. If this is your first time setting up Travis or any CI system at all, be patient, this is not the easiest thing in the world to do. But once it’s setup it should just work.

Using Docker To Run WordPress Integration Tests On Travis

Right now, we’re just running the unit tests. That’s a simple first step, but we also have a suite of integration tests to run as well. Because the unit tests are written in a way that does not require dependencies, we can just run those tests using the system PHP. In this case, the Docker environment Travis provisioned for us.

The integration tests require MySQL and WordPress running on localhost. We solved that problem for local development with a simple Docker environment created using Docker Compose. We can enable Docker and Docker Compose inside of the Travis environment by adding a “services” section to our .travis.yml. Once we’ve done that, our existing docker-compose.yml file and composer scripts are all we need.

In the “script” section, after running the unit tests, I added two commands. First, the preexisting composer script to install the docker environment, which provisions the test suite. Second, the command to run the integration tests.

Here is the new Travis file:

# Give sudo to environment
sudo: required

# Make Docker available inside the container
  - docker

# Use the PHP environment
language: php

# Don't send notifications via email, that's annoying
    on_success: never
    on_failure: never

# Trigger only on master -- we'll add Github pull requests in settings
    - master

# Cache composer dependencies
    - vendor
    - $HOME/.composer/cache

# Build these combinations of PHP and WordPress Versions
    - php: 7.2
      env: WP_VERSION=latest
    - php: 7.1
      env: WP_VERSION=latest
    - php: 7.2
      env: WP_VERSION=trunk

# Setup environment
  # Export composer
  - export PATH="$HOME/.composer/vendor/bin:$PATH"
  # Install plugin with composer
  - composer install --no-progress

# Run tests
  # Run just unit tests first -- if they fail we never spend the time building the environment for integration tests
  - composer unit-tests
  # Install full test environment using composer script
  - composer wp-install
  # Run integration tests
  - composer wp-tests
# IF tests passed run coverage and sniffs
  # Run coverage
  - vendor/bin/phpunit --coverage-clover=coverage.xml
  # Report to codecov
  - bash <(curl -s CODECOV_KEY

Installing the testing environment is one of the slowest parts of the build process. That’s why I am running unit tests first. That’s the fastest way to fail the build. If the code has a fatal error, for example, one caused by a bad git merge, the unit tests are not going to complete and the failure is reported without having to install the larger test suite. Since every build is actually multiple builds, total build time can increase significantly over time.

Continuing With Continuous Integration

Github pull request showing results of continuous integration
Because Travis is integrated with Github, we can see results of tests for each commit in a pull request.

Travis CI is one example of a continuous integration tool. I like the simplicity of Travis. Gitlab CI and CircleCI are alternatives that are a bit more complex. Those services are worth checking out.

Also keep in mind that, CI is the first half of CI/CD — continuous integration and continuous deployment. The CD part, is the process of automatically deploying changes to servers. If you’re implementing continuous integration for a WordPress site or WordPress-powered app, you can use a CI/CD service to update your site for you.

Once your automated tests for your site reach a point that you can trust that, if they pass, you trust the code, then you might as well have the code be deployed to your live site, or even better a QA site automatically. That’s all tedious work to do manually. These tests create

For plugin development, the deployment part involves building a release ZIP file and then using that to create an SVN commit on and/ or uploading the ZIP to your eCommerce site or marketplace. Travis has SVN installed and supports encrypted environment variables, so if you had a script to create a production build of your plugin, like this one in Gutenberg, you could create a build a commit it as a tag on or rysnc it to another location.

Running tests with phpunit is not the only type of tests you can run with Travis. For example, you might want to run the WordPress JavaScript test suite. Testing code and building production releases are not the only things Travis can do either. For example, you can analyze the quality of the code with a tool like Scrutinzer. Or run your lints, sniffs and code coverage reports, which is the topic of my next article in this series.

Josh is a WordPress developer and educator. He is the founder of Caldera Labs, makers of awesome WordPress tools including Caldera Forms — a drag and drop, responsive WordPress form builder. He teaches WordPress development at Caldera Learn.

The post Advanced OOP For WordPress Part 6: Continuous Integration For WordPress Plugins appeared first on Torque.

Read Full Article Here

How to Create a Custom Single Post Template (With and Without Coding)

How to Create a Custom Single Post Template (With and Without Coding)

WordPress templates make it easier for developers to create dynamic content and apply a consistent style across multiple posts or pages. While this is a very useful feature, it’s been skipped over by many users due to the required degree of coding.

However, this is no longer the case. The new Elementor Theme Builder includes the ability to create custom single post templates without doing any coding whatsoever. This opens up for new possibilities for every user, regardless of their coding expertise.

In this article, we’ll introduce you to single post templates and show you how you can create one yourself. We’ll cover both the standard, code-based method, and then demonstrate how you can use the Elementor Theme Builder to create a custom single post template without any coding at all. Let’s get started!

An Introduction to Single Post Templates

In a nutshell, you can use WordPress templates to apply a set of styles and content to a post or page. Post templates, in particular, enable you to create different designs you can apply to certain posts, without having to recreate the styling and format every time. It’s similar to how a stencil enables you to draw a certain shape over and over by giving you an outline you can fill with new content each time.

Depending on your site, this could be used in a variety of ways. You could use different templates for varying types of post content that require a specific layout. For example, a music site might use different templates for review posts and news articles. You could also use it to create a different template for each post author, or for featured content, to give just two more examples.

If this sounds like an amazingly useful feature, you’re not wrong! However, it’s one that’s been somewhat neglected by most WordPress users. This is because there’s not been an easy way to create your own custom single post templates without the need to do some coding, which can turn off many users with limited experience.

However, this is no longer a necessity, as there’s now a way to accomplish the same goal with no coding whatsoever. The rest of this article will be dedicated to showing you the different ways you can create a custom single post template.

How to Create a Custom Single Post Template Manually

The old school way of creating a post template is by cracking open your favorite text editor and doing it from scratch. However, this method will require you to be familiar with WordPress development. Naturally, this is a barrier for many, but having the expertise gives you more or less complete freedom to tailor the template to your satisfaction.

Before you proceed, you should make sure you’re using a child theme. This will enable you to edit your current theme without potentially losing those changes when you carry out an update to it.

Next, you’ll need to create a new file, which will form the basis of your template. For now, name it new-template.php and paste in the following code:

 * Template Name: New Template
 * Template Post Type: post
 get_header();  ?>

This defines your file as a post template, and fetch the header content using a hook. Of course, you should change the Template Name to anything you’d prefer. While you could upload the template to your site as-is, there’s no other content yet, so let’s add some.

If you don’t want to start from scratch, you can copy the contents of your theme’s existing single.php template file. You can do this by accessing your WordPress site using Secure Shell (SSH) or Secure File Transfer Protocol (SFTP) – we prefer using an open-source client such as FileZilla. The file you’re looking for will be in your child theme’s folder:

Open single.php and copy all of the contents below get_header(); ?>. This code determines how single posts appear in your current theme, so copy and paste it into new-template.php, after get_header(); ?>:

An example of a template file in a text editor.

At this point, you’re free to add any styling or other functionality to the template. This is where you’ll need to rely on your own development skills, but you can also refer to the WordPress Theme Handbook and this guide by WPBeginner for more information.

When you’ve finished your template, it’s time to upload it. Once again, you’ll need to connect via SSH or SFTP. Return to your child theme’s folder and add your new-template.php file within:

The new-template.php file added to the child theme folder.

This will add your post template to the theme, which you can test by navigating to a post or page within WordPress and looking for a new option within the Post Attributes metabox:

A drop-down menu with the available post templates.

With that, you’ve successfully created a post template manually!

Introducing the Elementor Pro Plugin

The Elementor plugin.

Next up, we’re going to look at how you can create a custom single post template yourself without coding. To do this, we’ll be using the very popular Elementor Pro. This is a premium version of the free Elementor page builder plugin for WordPress and is a drag-and-drop builder that enables you to update your theme using a live editor. Using it is a super easy way to quickly create a unique, professional look for your WordPress website.

The Pro edition ramps this up with additional features, one of which is the recently added Theme Builder. You can use this to create your own footers, headers, and also templates. We’ll be looking much closer at this later.

Key Features

  • Easy to use for beginners, with extensive options for advanced designers.
  • Uses an instant drag-and-drop interface that updates immediately when you make a change.
  • Enables you to create a responsive website for mobile devices.
  • Includes a large number of assets and templates to use.

Price: While the standard plugin is free, Elementor Pro (which features the Theme Builder) starts at $49.

How to Create a Single Post Template With Elementor Pro

The Elementor Pro extension.

We’re now going to create a custom template for single posts using Elementor Pro. You’ll, therefore, need to ensure you have both the Elementor plugin and the Elementor Pro extension installed and activated on your site.

First, you need to access Elementor > My Templates within WordPress. This is where you’ll find your custom templates, but will be empty initially:

The empty My Templates page.

Click Add New Template to get started, where you’ll first be asked what type of template you want to create. Since ours will be a single post template, select Single. You can also give your template a name here, but this is optional:

Creating your template.

Click Create Template and the Elementor Theme Builder will open, giving you the option to working with an existing template:

Selecting a template to start with.

You can choose to use one of these as a base for your own, or close this pop-up to create something from scratch. For this example, we’ll use one of the post templates, which we’ll add by clicking the Insert link that appears underneath its thumbnail when we hover over it. This opens the theme builder with the selected template:

The Elementor Theme Builder interface.

Once here, you have total freedom to edit your template. If you’ve not previously worked with Elementor, we recommend taking a moment to familiarize yourself with the basics. However, this is a very intuitive plugin so it shouldn’t take you long to get up to speed. You’ll find widgets and content in the left-hand menu, which you can drag-and-drop into the template:

Dragging a button widget into the post template.

To edit individual elements, select it and the menu will change to show its settings instead. This gives you a great deal of creative freedom, so add a few elements and see what you can make them do.

Editing the button using the left-hand menu.

For an even better idea of how your design will look in practice, you can use the Preview feature. This enables you to see how a selected post will look with your template. You can access it by clicking the ‘eye’-shaped icon within the bottom left panel, then selecting Settings:

Elementor's Preview Settings screen.

This will add a Preview Settings section to the main menu, where you can select the type of content to use. Select Post here, and choose your blog post from the second field:

The preview screen in Elementor.

Next, click Apply & Preview to reload the main editor to contain the selected post. You can now continue to edit your template and see how it will affect the look of the post in real-time:

A featured post template, using an existing post as a placeholder.

Once you’re happy with your template, it’s time to save and publish it. You can do this using the Publish button in the bottom left corner. When you click this, another pop-up will appear letting you determine where the template will be applied:

Setting the conditions for the post template.

This requires you to create conditions, which can be general or very specific, depending on the template’s purpose. You could choose to automatically apply it to every post on your site, or apply it to all posts in a single category:

Adding a condition.

You can also add multiple conditions to a template. For example, you could apply it to all posts within one category, but exclude posts with a specific tag. You can even specify individual posts. For this example, let’s make it easy for ourselves and choose Posts, which will apply it to all posts.

When you’ve added your conditions, you can click Publish to save your template. This will add the template to your library and apply it to all posts that match your specified conditions. Open any post on your site to see the template applied:

A post using the template created with Elementor.

You’ve now created the template successfully! You can go back and edit it however you like, or change the conditions to apply it to different posts altogether. Templates can also be added into posts and pages, so feel free to experiment with the feature and you’ll soon be able to create amazing reusable templates for your site!


Post templates are a useful WordPress feature that many users haven’t been able to use, as it’s historically required some coding to implement. However, the Elementor Theme Builder has opened custom post templates up to a wider audience. Anybody can now create their own single post templates without touching a single line of code.

In this article, we’ve covered how you can create a custom single post template. There are two methods of doing this, with the classic solution requiring you to using code to manually create the template. However, we’ve also shown you how to use the Elementor Pro plugin to do the same job using its Theme Builder.

Do you have any questions about using custom single post templates? Let us know in the comments section below!

Image credit: rawpixel.

John Hughes

John is a blogging addict, WordPress fanatic, and a staff writer for WordCandy.

The post How to Create a Custom Single Post Template (With and Without Coding) appeared first on Torque.

Read Full Article Here

Why Millions of Developers use JavaScript for Web Application Development

Advanced OOP For WordPress: Customizing REST API Endpoints To Improve WordPress Search

Over the past 20 years or so since when JavaScript was released, it has become the most popular programming language for web development today. You can understand the importance of JavaScript as a web development language from the fact that as per the recent reports, JavaScript is currently being used by more than 94 percent of all the websites.

JavaScript is a client-side programming language which helps web developer to do Web Application Development and make dynamic and interactive web pages by implementing custom client-side scripts. Developers can also use cross-platform runtime engines like Node.js to write server-side code in JavaScript. Developers can also create web pages which works well across various browsers, platforms, and devices by combining JavaScript, HTML5, and CSS3.

There are many JavaScript Frameworks available in the web market like AngularJS, ReactJS, NodeJS etc. By using these frameworks, you can reduce the amount of time and efforts required for developing JS based sites and apps. JavaScript allows the programmers to build large-scale web application easily. It simplifies the whole process of developing large-scale web applications.

SlashData’s Developer Economics is one of the leading research programs on mobile, desktop, IoT, cloud, Web, AR, VR, game, and machine learning developers. It tracks the developer experience across platform based on thousands of developers annually. As per its 14th Developer Economics global survey, the following developers trends for 2018 emerged:-

  • SlashData report says the future is AI and the related emerging technologies like self-driving cars, brain computer interface etc will make biggest impact in the next 5 years.
  • Developers now adopting serverless platforms to reduce cost by paying for only what they use.
  • AR is an emerging as hot technology for developers with both companies Apple and Google releasing inbuilt AR on their smartphone platforms. For AR/VR both companies are targeting the devices that customers already use i.e smartphones and desktops.
  • SlashData also presents an estimate for the number of active software developers using various programming languages used across the globe.

This report says, JavaScript is the most popular programming language used by about 10 million developers worldwide. At second place is Java and Python is also catching up with 6.3 Million active developers. The rise of machine learning is pushing Python up.

Why a WordPress Developer Needs to Learn JavaScript?

JavaScript is extensively used by the web developers to create various web applications and to add interactive features to them. Most of the internet browsers support JavaScript, which allows dynamic content to get displayed beautifully on web pages. WordPress is the most popular CMS today and JavaScript also plays an important role in WordPress development. A web developer with good knowledge of JavaScript can make different applications robust and scalable. If you want to be an expert WordPress developer then you need to learn JavaScript so that you can make smart decisions right from the beginning.

Also, many of the WordPress themes and plugins have been created with extensive use of JavaScript. JavaScript also comes bundled with WordPress in the form of various JavaScript libraries, such as jQueryJSONBackbone.js, and Underscore.js. Hence if you know JavaScript then you can understand, customize and use them better in your WordPress website development.

JavaScript is also being increasingly used in WordPress admin in recent releases and this trend is likely to continue in future. Recently Calypso, an entirely JavaScript powered version of WordPress admin was released.

You can use the below tips to make your work lot easier:

Learn Basics of JavaScript

Learning the basics of JavaScript will help you to understand the required JavaScript skills that are utilized in WordPress development.

Choose the Right JavaScript Framework

You should have basic knowledge of different JavaScript frameworks. Popular JavaScript Frameworks are:

  • Angular
  • ReactJS
  • Ember.js
  • Vue.js

Using JavaScript Framework, you can finish the creation of JavaScript applications quickly. If you are an active WordPress developer then you should have sufficient knowledge of HTML, CSS, and JavaScript. You can use any of the JavaScript frameworks but initially, you should choose React or AngularJS to perform web development work.

The needs of WordPress developers can be divided into two main categories: backend and frontend. If you are into frontend development, you have many options to choose from but if you are a backend developer then you can choose Node.js easily.

Become Proficient in JavaScript

Although you can start WordPress development even with a little knowledge of JS, you should soon aim for becoming proficient. This will help you to develop user-friendly web applications.

Overall it’s clear that JavaScript is a great option for WordPress users.

Now let’s discuss the advantages of using JavaScript for your next web application development project and to know why it still remains the most popular web application development language.

JavaScript is Cross Browser Compatible

One of the good things about JavaScript is that it is supported by multiple web browsers like Google Chrome, Internet Explorer, Firefox, Safari, and Opera etc. Hence the users can access the web applications on any web browser of their choice easily. They can just enable the JavaScript language if it is disabled and can enjoy all the functionality of the site.

JavaScript comes with lots of Libraries and Frameworks

JavaScript Frameworks and libraries make it easy for web developers to build large, JavaScript-based web applications. There are many dynamic JS frameworks like AngularJS, ReactJS, EmberJS etc. Using these frameworks, developers can easily, quickly, and efficiently develop highly interactive and professional looking web applications. JavaScript also has lots of libraries which you can use as per your requirements. For example, you can do GUI development using widgets like Bootstrap, jQuery or AngularJS.

Easy to Write JavaScript Code without using any Specific Tool

You can write the JavaScript code easily without using any particular type of program or tool. You can just open a notepad and write your JavaScript code. You can use many editors to find out the mistakes in the JavaScript code. The editor reformats the JavaScript code and allows you to discover the bugs and error quickly and easily.

Simplify Complex Web Application Development

JavaScript is an interpreted programming language still it simplifies development of complex web applications by allowing the developers to simplify the application’s composition. The developers can use JavaScript libraries to create DOM boundaries. This shadow DOM further makes web browsers deliver documents with widely used HTML tags like select, div and input.

Responsive Web Design

Nowadays most developers do responsive web design to make a website accessible and work well across multiple browsers and devices like smartphones and desktops. Responsive web design enables the developers to optimize the site for both computers and mobile devices using the same code. The developers have to combine the CSS3, HTML5, and JavaScript to make the web pages responsive. The developers can use JavaScript to optimize web pages for mobile devices.

Google AMP Project

Google has started the Accelerated Mobile Pages(AMP) project to create websites which deliver richer user experience across various mobile devices. Google has implemented many optimization techniques to increase the loading speed of the mobile web pages and it requires developers to integrate AMP technology into the web pages by using HTML5, CSS3, and JavaScript. Means the developers have to use JavaScript for optimizing websites for mobile devices for AMP.


As we have discussed, there are several reasons why JavaScript has become the most popular programming language in the world among various type of developers including WordPress developers. JavaScript is a robust programming language that helps developers in building large scale web applications easily and quickly.

JavaScript not only lets you build a highly interactive web app but it also helps in enhancing the speed, performance, functionality, usability, and features of the application without any hassle. Now developers and programmers are increasingly using JavaScript to make their web applications deliver best and optimal user experience across various devices, browsers, and operating systems. Developers should also learn about various JavaScript libraries, frameworks, and tools and combine multiple libraries and frameworks to use the JavaScript as per the requirements of the projects.

Being an experienced software developer at Xicom Technologies, Judi Toledo is passionate about web & mobile technologies. Researching on new technology that could help to enhance software functionalities. She keeps eye on the latest happening in the software industry to remain updated with the current market trends.

The post Why Millions of Developers use JavaScript for Web Application Development appeared first on Torque.

Read Full Article Here

A Beginners’ Guide to Privacy Policies

A laptop showing the EU flag with a padlock inside.

Among the important web development trends of 2018, user privacy and how websites handle collected data is at the top of the list. With the imminent introduction of the General Data Protection Regulation (GDPR), it’s more important than ever to ensure you have a privacy policy in place that adheres to its guidelines. Failing to do so could mean incurring severe penalties.

Fortunately, user privacy isn’t an impenetrable topic. There are a few key elements you’ll need to consider, as well as some tools that can help you put the optimal policy in place. There’s the obligatory WordPress plugin solution, but also comprehensive third-party offerings that constantly update based on changes made to your site’s elements.

In this post, we’ll explore what a privacy policy is and why you need one. Then we’ll cover five different ways to implement a privacy policy on your website. Let’s get started!

What a Privacy Policy Is

In a nutshell, a privacy policy is a legal document outlining your approach to managing user data. It explains what data you collect, how it’s used, where it’s stored, and anything else appropriate that your users need to know about the privacy of their collected data. For example, we have our own privacy policy linked to within the footer of every page:

Privacy policies are part of the same family as ‘cookie notices’ (i.e. website banners displaying whether a site collects cookie information). This is because both are implemented to clearly inform users that their data is being collected, as well as why and how.

As you can imagine, privacy policies can run to either a few lines or reams of detailed legal verbiage (although that would likely hamper the reader’s understanding). In short, you’ll usually find the following:

  • Clarification on what constitutes a user, the website, and any other relevant party.
  • Information on how data is collected on your site.
  • An overview of how the collected data is used once it’s been obtained.
  • What the visitor can do to make sure their data is deleted.

You may find that some privacy policies don’t include some of this information currently. However, as we’ll explain, all websites will shortly be required to add these elements, with heavy penalties facing those who do not comply.

Why a Privacy Policy Is Necessary For WordPress Websites

As we mentioned, the EU Cookie Law is almost a precursor to initiatives being introduced this year. The GDPR radically overhauls compliance for practically every website, and in contrast to the current Cookie Law, will include stiff penalties for those not complying with the directive.

While the GDPR, Cookie Law, and implementing a privacy policy, in general, is platform-agnostic, for WordPress users the waters become a little more muddied. For starters, there are many cogs that turn to drive the entire platform – elements such the plugins and themes you use will log data, for example.

What’s more, many users will have third-party tools and solutions that help them manage a site day-to-day, which is to be expected. If you or your clients use tools such as Google Analytics or InspectLet, these will also capture user data, meaning your privacy policy needs to reference this too.

It’s definitely a minefield, but one you will have to traverse if you want to stay on the right side of the law. Our advice is that if you’re considering this option solely based on the amount of work it will take to implement, it’s not a wise idea. The GDPR will mean authorities have the power to dish out millions of dollars worth of fines to non-complying sites. In short, the buck stops with you.

5 Solutions For Implementing a Privacy Policy on Your Website

Let’s take a look now at how to implement your privacy policy simply and effectively. Each of the solutions below is GDPR-friendly and are comprehensive enough (or have the scope) to handle any custom user privacy situation you or your clients may have. Let’s take a look!

1. Manually Create a Privacy Policy

First off, there’s nothing wrong with manually creating your own privacy policy if you feel it’s warranted. After all, it’s usually just a detailed statement of how you’ll capture and use visitor data. For websites with either zero or very little in the way of data collection, this method may be ideal.

We’ve mentioned what a privacy policy should contain already, but just to reiterate, you should include:

  • Details on the information you collect, and how you do so.
  • Why you’re collecting the information.
  • Whether third-party services associated with your site collect information, and the details (such as ad networks).
  • Clear guidance on whether users can opt out of data collection, and contact details in order to discuss things further.

However, unless you get the wording exactly right, your privacy policy could land you in hot water should any data breaches occur. Of course, you could get your privacy policy looked over by a legal professional, but you may find more value in a dedicated service. Let’s take a look at the rest of the options.

2. iubenda

The iubenda website.

In our opinion, iubenda is the most comprehensive and easy to use service available, and we really like the concept. Because many websites (especially WordPress-powered ones) are made up of many moving parts, you’ll likely have various data collection points throughout your site’s code. Keeping tabs on all of these could be difficult, but iubenda’s module-based system makes the process a breeze.

In short, you’ll piece together your privacy policy from a comprehensive list of services, resulting in a complete, ready to roll page that can be embedded or linked to as you wish. What’s more, each module is updated automatically when required. It’s going to be a great timesaver for high-traffic sites, or those handling sensitive data. However, it’s probably overkill for smaller blog-type sites.

As for pricing, it’s incredibly reasonable at its core. Ultimately, while there’s a free plan, you’re likely better off purchasing a license starting at $27 per year for one site, or a multi-license for $9 per month.

3. Shopify Privacy Policy Generator

The Shopify Privacy Policy Generator is (unsurprisingly) from the Shopify team – a leading non-WordPress specific ecommerce solution. Given that their business is heavily-focused on leveraging user data, it makes sense that they provide helpful tools for their user base. This particular service will be suitable for any e-commerce site owner, and what’s more, it’s completely free to use.

In a nutshell, this solution is just like creating your own privacy policy. Once you provide some essential details, you receive a tailored privacy policy in text form, which you can then paste into a post or page:

The Shopify Privacy Policy Generator.

It’s arguably the quickest and simplest solution available, which makes it great for Minimum Viable Products (MVPs) and startups in need of a quick launch. However, because it’s essentially a one-size-fits-all solution, it could miss out vital aspects of your site. In addition, it’s not WordPress-specific, so it won’t offer the same detail as other policies.

4. Auto Terms of Service and Privacy Policy

The Auto Terms of Service and Privacy Policy plugin.

As for WordPress plugins, Auto Terms of Service and Privacy Policy is one of the best available for creating clear-cut, and comprehensive privacy policies. By using this plugin, you’ll be amending the Terms of Service (TOS) and privacy policy of Automattic – the developers of WordPress – meaning it’s totally free to use.

It’s similar to Shopify, in that you’re adding your own details to a template privacy policy. However, Auto Terms of Service and Privacy Policy allows you to configure a more robust solution tailored to the specific requirements of your website. It’s also extremely easy to use.

Overall, Auto Terms of Service and Privacy Policy is going to be great for those needing a quick way to protect themselves temporarily, and the fact that it’s a WordPress plugin is a major plus.

5. TermsFeed

The TermsFeed website.

Finally, we have TermsFeed. This is one of the more popular third-party privacy policy generators, and it works in a similar vein to iubenda. In essence, you select what to include, and TermsFeed generates a privacy policy you can link to or embed, which is then updated automatically.

The main perk of TermsFeed is the vast number of different policies you can generate:

Examples of the policies you can create with TermsFeed.

We’d arguably put this aspect ahead of iubenda’s, although both services are pretty similar overall. However, where TermsFeed falls down is its ambiguous approach to pricing. While there’s a clause-limited free service, premium policies require a one-time payment that is calculated upon creation. Because of this, it’s likely not going to be a solution for the budget-conscious.


Making sure you have a privacy policy in place before ‘GDPR doomsday’ should, naturally, be a high-priority task. It’s not necessarily easy, but one you’ll want to undertake given the potential to be fined for a misstep.

This post looked at five ways to create a GDPR-friendly privacy policy for your website. Let’s recap them quickly:

  1. Manually create a privacy policy. If you can access the legal know-how, writing your own privacy policy is a great option.
  2. iubenda. A comprehensive service ideal for the vast majority of websites.
  3. Shopify Privacy Policy Generator. This solution can’t be beat for a quick e-commerce privacy policy template.
  4. Auto Terms of Service and Privacy Policy. As WordPress plugins go, this is a must-have for generating a quick privacy policy.
  5. TermsFeed. While this is also a comprehensive solution, you’ll likely need a decent budget to create your privacy policy.

Do you have a question about how to implement a privacy policy on your WordPress website? Ask away in the comments section below!

Featured image: mohamed_hassan.

John Hughes

John is a blogging addict, WordPress fanatic, and a staff writer for WordCandy.

The post A Beginners’ Guide to Privacy Policies appeared first on Torque.

Read Full Article Here

How to Vet & Hire a WordPress Subcontractor

How to Vet & Hire a WordPress Subcontractor

Hiring a virtual assistant or multiple subcontractors can be one of the best decisions you can make for your WordPress business. They can take care of the tasks you aren’t well-versed in, or the tasks that require a disproportionate amount of time for the return they provide. Delegating tasks such as these frees up your […]

Read Full Article Here

Advanced OOP For WordPress Part 5: Using The WordPress Test Suite For Integration Testing

How to make your WordPress Posts go Viral

In my last article, in this series on advanced object-oriented programming (OOP) for PHP WordPress development, I showed how to setup the WordPress test suite for integration tests. Previously, I had written about unit tests, which I showed how to run in an isolated environment. These tests were not dependent on WordPress at all, so they could just run on the system’s PHP.

On the other hand, integration tests cover the interaction of the plugin and WordPress, so they need a complete WordPress. I showed how to setup those tests using VVV or Docker. In the example plugin, I set up the integration tests to run with Docker. I think that the initial setup for Docker is about the same, if not easier than setting up Vagrant and VVV. Creating a WordPress environment, from scratch, that is suitable for local development and running automated tests for PHP and JavaScript as part of a continuous integration and deployment system is much simpler with Docker than Vagrant. I showed the one file that is needed to create that Docker file in my last post. I could do something similar with Vagrant, I think, but I do not know Ansible or Puppet or whatever type of server provisioning scripting system I would need to do this without Docker.

I don’t want to learn all that. Instead, I want to go to the plugin I have and type one command to install the environment — composer wp-install — and one to run the integration tests — composer wp-tests. That’s all setup, now it’s time to talk about how to write these tests. Specifically, let’s look at how the assumptions we are willing to make are different when writing integration tests as opposed to unit tests.

Reversing Our Assumptions

In my article about unit testing, I talked about how some of the tests were based on the assumption that WordPress would work properly. Based on that assumption, I wrote tests that relied on mock data. Those assumptions allow those tests to prove that the code’s public API is consistent and that the core function — what is done with the input — works.The weakness of the assumption unit tests are based on, and implicated on a practical level by isolating out all side effects — is we’re assuming the connection to WordPress is properly connected, will have consistent output and the consistent output will produce the right effect on WordPress. Integration tests make the opposite assumption — we assume our code is working in isolation and we test its effects without isolation.

If we were making sinks, we’d write unit tests to make sure faucets turned on and off and produced hot or cold water as directed and then we’d write an integration test to make sure the water went into the sink instead of just pouring out onto the floor, or some of it going in the sink and some of it leaking out of the pipe too soon.

Writing The Tests

What Do We Test?

The code we’ve created so far affects WordPress in two ways — it adds a filter that results in different WP_Query and REST API results. So, we need to test that the effect of this code is the filter was added in the way we wanted it to be as well as that in the right situations WP_Query and REST API results are modified the way we expect and that there are no effects when there should not be.

Testing Adding and Removing Filters

For this first group of tests, we’re just looking to prove that our code can add and remove hooks properly. The class FilterWPQuery has a method addFilter() and a method called removeFilter(). We can cover those interactions by testing that addFilter() causes WordPress to report that the filter was added. We can also test that removeFilter() causes WordPress to report that the filter was removed.

Other tests we have cover what happens if the filter is added. WordPress core has tests to cover hooks. This is is enough for covering this effect.

To test that the hook is added, we’ll instantiate the class and use it to add the filter and then use PHPUnit to assert that the result of has_filter() is what we would expect if the filter was added:

View the code on Gist.

To test that the hook can be removed, we’ll instantiate the class and use it to add and then remove the filter and then use PHPUnit to assert that the result of has_filter() is what we would expect if the filter was added and then removed:

View the code on Gist.

Those two tests prove that we can effect WordPress. Before we move on to testing how we effect WordPress, is to test that the filters do not have unintended side effects. We’re testing a system that sometimes modifies what posts WP_Query will return, we need to make sure our system doesn’t always modify what posts WP_Query returns.

Our system is designed to modify WP_Query, when it is used by a specific REST API route. Later, we’ll test that route. For now, we’ll add our filter and then insert one post into the database, then check if its the post that a WP_Query for all posts returns. That’s what it’s supposed to do by default, let’s make sure it still does this when we add our filter.

View the code on Gist.

In this test, we use the post factory from the WordPress test suite to create the post. A class that implements the factory pattern, which I covered in a previous Torque post, is a class that creates objects of other classes.

One great use for the factory pattern is creating test data. By having a single, standard method for creating a type of test data — in this case WordPress posts — decreases code repetition and ensures we can trust our test data. It also makes it easier to write tests.

The post that is created with the post factory is what our tests are asserting the result of the query is the same as. The factory creates our expected result, that our tests compare against. We do not need to test every part of the resulting post, WordPress core’s tests covers WP_Post.

Testing WP_Query Results

We have not yet gotten to the point where the WP_Query results are anything but mock data. We want tests that prove that the whole system is reliable, by the standard of it always outputs an array of WP_Post objects that is the right size.

Later on we can change what happens internally, don’t worry we are almost to that article. When we do, the new code will need new unit tests. But we will not need new integrations tests. In fact, when we implement a different system for running the search, for example ElasticSearch or SearchWP, we should make it a requirement that these integration tests pass without any modification.

All of this functionality is encapsulated in the getPosts() method. So the two tests we need to cover that method are one to prove it returns an array and another that the array has the right WP_Posts.

Testing that that getPosts() returns an array is simple. We write a test to assert that the result of the function that is_array() when passed the results of getPosts() is true. We’re proving it is an array:

View the code on Gist.

That test covered what the type of results — the results of the type of array. The next test covers the contents of the results — the array contains WP_Posts. For this, we’re going to use getPosts() to get the array of posts and loop through the results, asserting that each one is a WP_Post:

View the code on Gist.

Testing REST API Routes

All of those tests prove that WP_Query would produce the results we expect it to, when we tell it we are in the right context. That’s good, but it doesn’t prove that the results will be correct in that context. Now it’s time to test the effect our code has on the REST API responses that it is designed to modify.

I have covered testing REST API endpoints before for Torque. That article covered custom endpoints. These next tests cover modified default endpoints. But the way we test is similar. We’re not going to make an actual HTTP request — that would get us into acceptance testing. We’re going to use a mock WP_REST_Server, the same one WordPress core tests use.

We have to trust the assumption that WordPress mock WP_REST_Server accurately reproduces the behaviour of the WordPress REST API. That assumption can be made because of WordPress core’s test suite. If you find a problem with WordPress’ tests that cover the WordPress REST API, then you should open an issue in core trac and submit a patch.

We’ll need two tests. One to test that that the conditional logic in our system, which should return true in this context. The second test will prove that the results are the results our system should generate.

Here is our first test, it dispatches the request and asserts that the shouldFilter() return true:

View the code on Gist.

That proves that the system knows it should filter the results. Now let’s prove the contents of the result set are correct. This is very similar to the tests of the WP_Query results. We are just checking that we see the right WordPress posts resulting from the REST API being used in its natural way. We’re testing just the effect of our system.

This test starts the same as the last one, by creating a mock request. This time we loop through the results and compare them to the output of the method getPosts(). That’s exactly the same method that is being used underneath. They should produce the same results. If something was wrong with our code, this test would be comparing those expected results to a WP_Error object or some other set of results and therefore the tests would fail.

What’s cool about this pattern, is that when the getPosts() method changes, so does the data the tests is comparing against. This test doesn’t check for any specific data — other tests can do that. It just makes sure these two different ways of accessing the same data stay in sync.

That may seem like a small point. It’s not because previous to these tests, we have written or identified tests that make it safe for this test to make a small number of assertions and cover a lot of functionality of the system, most of which we don’t control.

This last test becomes the ultimate test of our system. It’s the final result. But it’s no different than every other test. Each one proves one small thing and assumes every other test is passing. Testing is all about safe assumptions. Once one test fails, all assumptions are untrusted.

In the next article in this series, I will cover setting up Travis CI to run the tests, in multiple environments on all pull requests created in the Github repo for the plugin. This kind of testing automation, combined with a git-flow workflow will enforce that in the future all changes to the code require all of the tests to pass. We call this testing automation continuous integration or CI for short.

Thinking About Assumptions

My strategy for unit and integration testing, and using a different environment for each type of testing does rely on some assumptions that are worth questioning. For example, there are very complete mocking frameworks like WP_Mock and Mockery that could provide reliable enough data that I could test my integration with WordPress without having a WordPress site.

I’m going this way because I think it’s easier to teach and understanding how to use phpunit for isolating unit testing is a precursor to being able to use it with other tools. Using phpunit with the WordPress test suite, like we just did was a practical example of another tool. Many of the other tools we might want to work with, for example, Behat, a PHP behavior-driven testing framework that we can use with WordPress thanks to WordHat, require phpunit and local test environment like this series is using for integration tests.

I hope that you’ve seen what assumptions we had to make in this article and can look at the benefits and weaknesses of the different approaches as you evaluate which of these testing tools are best for your workflow.

Josh is a WordPress developer and educator. He is the founder of Caldera Labs, makers of awesome WordPress tools including Caldera Forms — a drag and drop, responsive WordPress form builder. He teaches WordPress development at Caldera Learn.

The post Advanced OOP For WordPress Part 5: Using The WordPress Test Suite For Integration Testing appeared first on Torque.

Read Full Article Here

3 Common WordPress Attacks You Can Stop In Their Tracks

A stop sign.

Despite the thousands of hours that have gone into making sure WordPress is secure and stable, the default platform still has certain aspects that are vulnerable to attacks. It’s vital to know what those attacks are, so you can take steps to bolster your security and provide needed peace of mind.

As we discussed in a previous article, code injection attacks – such as Cross-Site Scripting and SQL injection – remain a high-priority concern for many website owners. Fortunately, protecting your site from these intrusions is simply a case of using some common-sense techniques, along with a snippet or two of code.

In this post, we’ll take a cue from the official WordPress developer website, and run through some of the most common attacks the platform has to contend with. Plus, we’ll also discuss how to fix them. Let’s get started!

What WordPress Already Does to Fight Hackers

WordPress takes security very seriously, as demonstrated by the dedicated page on the official website.

It’s worth mentioning up front that WordPress is already highly secure, which is what you’d expect from a platform that powers so much of the web. However, if you were to go by WordPress’ portrayal in the media, you’d be forgiven for thinking it was an insecure platform not suitable for professional use. Of course, nothing could be further from the truth.

On their security page, the WordPress team clearly outlines their commitment to closing off potential hacker entry points. This includes:

  1. Presenting fixes on an almost constant basis, via regular incremental and point updates.
  2. A commitment to backward compatibility, which encourages users to install those regular updates.

Despite all of this effort, WordPress – much like every web application and Content Management System (CMS) – still needs an occasional helping hand to stop intrusions. The good news is that this is something completely within your control.

3 Common WordPress Attacks You Can Stop in Their Tracks

As we mentioned above, no platform can ever be completely safe. In this section, we’ll cover three of the most common attacks according to the WordPress development team, and discuss how you can keep them at bay.

1. Cross-Site Scripting (XSS)

First up, Cross-Site Scripting (XSS) is one of OWASP’s top ten security risks, so it’s worth paying special attention to. It’s a member of the ‘injection’ group of attacks and happens when JavaScript is loaded via vulnerable dynamic site elements – such as contact forms and other user input fields. A notable case of a severe XSS attack occurred in 2013, targeting Yahoo. This attack left user accounts in the hands of hackers.

As you can imagine, an XSS attack could severely reduce the trust customers place in your (or your client’s) business. As such, taking the measures necessary to prevent such an attack should be a priority. Fortunately, you can stamp out XSS by simply escaping your outputs correctly, and stripping away unwanted data.

Take this piece of HTML, for example:

<img src="<?php echo esc_url( $great_user_picture_url ); ?>" />

The esc_url() function is specific to WordPress and replaces certain characters to prevent XSS attacks. For another example, check out this snippet:

$allowed_html = array(
    'a' => array(
        'href' => array(),
        'title' => array()
    'br' => array(),
    'em' => array(),
    'strong' => array(),
echo wp_kses( $custom_content, $allowed_html );

Here, wp_kses() has been used to allow only the specified HTML elements and attributes to occur in a string.

These are two handy WordPress-specific functions to combat XSS in your own projects. Using these and similar measures is a smart way to tighten your site’s security.

2. SQL Injection

SQL injection is closely related to XSS, in that it requires a vulnerable entry point based on your sanitization efforts. However, the difference here is that these attacks directly affect your database, which can have disastrous consequences. SQL injection can affect any site, most notably NASA way back in 2009. Fortunately, WordPress makes it relatively easy to stave off SQL injection attacks.

The standard WordPress APIs provide a number of functions to help protect inputted data from SQL injections. For example, add_post_meta() offers you a secure way of using SQL’s INSERT INTO command, meaning you don’t have to add database calls manually to your code.

Of course, some of your SQL queries aren’t going to be this simple, and there’s a chance the API won’t account for them. In these situations, you’ll want to turn to the wpdb class. Here’s an example of how that works:

$wpdb->get_var( $wpdb->prepare(
  "SELECT something FROM table WHERE foo = %s and status = %d",
  $name, // an unescaped string (function will do the sanitization for you)
  $status // an untrusted integer (function will do the sanitization for you)
) );

As you can see, we’ve used the $wpdb->prepare() function, which escapes the SQL query before executing it. This is just the tip of the iceberg, and there’s plenty more under the hood of WordPress to help halt SQL injection attacks.

3. Cross-Site Request Forgery (CSRF)

Finally, we have CSRFs – pronounced “sea-surfs.” In short, this is where an oblivious user is tricked into performing an action of the attacker’s choosing. To understand how this attack works, it’s worth considering how simple requests (such as clicking a link) work under the hood. Ultimately, these requests are one of two types: GET or POST. The former is a request for a page, and the latter is when data is sent to the server.

Consider a Google search for WordPress, where browsing to Google initiates a GET response, and searching for WordPress becomes the POST request. A CSRF is when this happens without the user’s consent. YouTube is one of many websites to succumb to this attack, and if a site that prominent can be vulnerable, you’ll need to do all you can to keep your site as safe as possible.

The solution here is to use ‘nonces’ – single-use security tokens designed to protect URLs and forms from being compromised. Take a look at this code example:

<form method="post">
   <!-- some inputs here ... -->
   <?php wp_nonce_field( 'name_of_my_action', 'name_of_nonce_field' ); ?>

Here, we’ve used the wp_nonce_field() function to add a nonce to our form. This will guarantee that the user intends to perform the action (i.e. submitting the form) as expected and that there’s nothing they need to do on the front end.

Validation of the nonce doesn’t require setting any specific parameters, but there are options relating to the input action and name that can make your nonce more secure. What’s more, there are also functions to add nonces to a URL, as well as a custom format that’s ideal for AJAX requests.


A platform that powers about 30% of the web needs to be rock-solid, and this is definitely true of WordPress. However, no platform can guarantee 100% security. Some attacks can cripple a WordPress website, so you need to do what you can to ensure that malicious users have a hard time trying to hack your website.

To get you started, we’ve looked at three common WordPress attacks and how to fix them. Let’s recap each quickly:

  1. Cross-Site Scripting: This attack can be fixed by correctly escaping your outputs.
  2. SQL Injection: This related attack takes advantage of poor data sanitization to access your SQL database.
  3. Cross-Site Request Forgery: WordPress nonces can help validate a user action, and guarantee that it’s legitimate.

Have you ever been affected by any of these vulnerabilities, and if so, what was the outcome? Share your stories in the comments section below!

Featured image: dimitrisvetsikas1969.

John Hughes

John is a blogging addict, WordPress fanatic, and a staff writer for WordCandy.

The post 3 Common WordPress Attacks You Can Stop In Their Tracks appeared first on Torque.

Read Full Article Here