Monday 31 October 2022

Managed WordPress Hosting vs VPS (Buyer’s Guide)

Choosing a hosting plan is one of the most important considerations when creating a website since it affects your site’s speed, security, and availability. VPS and managed WordPress are two popular options. However, you might not fully understand the difference between these two choices.

Fortunately, choosing a hosting provider is easier when you know what you’re looking for. While there are pros and cons to both managed WordPress hosting and VPS hosting, they are suitable for different kinds of web users.

In this post, we’ll introduce you to VPS vs. managed WordPress hosting. Then, we’ll explore the main pros and cons of each type of hosting. Let’s get started!

An Introduction to Managed WordPress Hosting

Managed WordPress hosting is a package that includes the usual server space and resources for your website. You’ll also get access to additional site management services, such as security, migration tools, database maintenance, and optimization. Additionally, the hosting plan is designed specifically for WordPress websites.

For instance, at DreamHost, our managed WordPress hosting plans provide built-in caching for fast performance:

managed WordPress hosting

We also throw in a free migration service and a staging area so that you can test out changes before altering your live site. What’s more, you’ll get a pre-installed SSL certificate, daily backups, and 24/7 expert support.

Due to the inclusion of additional services, managed WordPress hosting is typically an excellent option for beginners. Alternatively, it can be a great choice for users who don’t want the responsibility of ongoing site maintenance.

Running a website can be demanding. Therefore, choosing a managed hosting solution can free up time for you to focus on creating content and growing your business.

Managed WordPress Hosting: Pros & Cons

The Pros of Managed WordPress Hosting

There are many advantages to choosing managed WordPress hosting over other solutions:

Simplicity

Managed hosting is one of the most stress-free ways to set up your website. You don’t have to worry about running updates or backing up your site, among other administrative tasks.

Security 

Since your website is in the hands of trusted professionals, if anything goes wrong, it’s often sorted out quickly. Plus, you can benefit from advanced security features like malware scanning and defense against cyber attacks.

Scale

Managed hosting providers have the resources to handle sharp traffic spikes as opposed to other setups like shared hosting. As a result, you don’t have to worry about your site going down during busy periods.

WordPress-Specific Perks

Many managed WordPress hosting providers provide extra features to benefit your WordPress site such as one-click installs, staging environments, and version control.

Performance

Managed WordPress hosting servers are often optimized for WordPress performance and fast loading times.

Support

Not only can you access quick help with server-related issues, but support teams have been trained to work with WordPress. Therefore, you can access expert advice related specifically to the CMS.

At DreamHost, we pride ourselves on top-notch support because we understand how frustrating it can be when things go wrong:

hosting customer support

You can browse our knowledge base to find quick, convenient solutions. Alternatively, you can join a discussion forum to get tried-and-tested advice from real users. If you’re still stuck, you can log in to your panel and reach our tech support team, who are available 24/7.

The Cons of Managed WordPress Hosting

While there are many benefits to choosing managed hosting plans, it’s also important to be aware of the drawbacks:

Less Control

This can sometimes be a good thing if you don’t want accountability. However, if you’re an experienced user who can manage your server settings, you’re placing your site in control of others. Additionally, you might be unable to use some plugins if they’re incompatible with your host’s architecture.

Limited Use 

Typically, managed hosting providers only work with WordPress. Therefore, solutions don’t always account for other CMS platforms or development use cases. Plus, most plans only accommodate a limited number of websites, so paying for extra sites can quickly become expensive.

Cost

With all the additional services included in managed WordPress hosting, you might end up paying more than VPS hosting. However, prices are more competitive than ever due to the popularity of this hosting method. Plus, you’re essentially gaining access to a dedicated web team since many providers offer 24/7 support and handle everything for you.

Overall, if you use lots of third-party software for added functionality or you’d like the flexibility to configure your server, managed WordPress hosting might not be the best choice for you.

Do More with DreamPress

DreamPress Plus and Pro users get access to Jetpack Professional (and 200+ premium themes) at no added cost!

managed WordPress hosting provider

An Introduction to VPS Hosting

With VPS hosting, your website will be hosted on a virtualized part of a server. It works similarly to shared hosting since you still share a physical server. However, your files and resources are separate from other websites on the server.

VPS eliminates the main drawback of shared hosting since downtime is less likely to occur from competing for resources. Instead, each website hosted on the server will be allocated a set amount of files.

For this reason, VPS hosting combines many of the best features of shared hosting and dedicated hosting. While the server doesn’t belong to you entirely, it’s a much cheaper alternative that comes close to a dedicated instance.

Typically, you’ll benefit from more control and flexibility with VPS hosting compared to managed hosting plans. Still, fully taking advantage of this solution can require some technical knowledge. Plus, it may also require more time and effort to maintain, and you’ll be solely responsible for managing your site.

Get Content Delivered Straight to Your Inbox

Subscribe to our blog and receive great content just like this delivered straight to your inbox.

VPS Hosting: Pros & Cons

The Pros of VPS Hosting

While it may not be the right choice for every user, there are many benefits to choosing VPS hosting for your website.

Control

You’ll be in the front seat of running and maintaining your site. This unlocks many possibilities, such as configuring your server to your exact specifications and installing third-party software.

Flexibility

Unlike managed WordPress hosting, you aren’t bound to WordPress. In fact, you can host any kind of application on any system you like.

Freedom

Rather than discussing what you can do with VPS hosting, it’s easier to talk about what you can’t do (and there isn’t much). You can pretty much achieve anything you want as long as you possess the technical knowledge to configure it.

Security

Managed WordPress hosting takes care of all your security needs. However, if you know what you’re doing, you can enjoy air-tight security with VPS hosting. There will be fewer sites on your server with solid separation, so the risk of cross-infection is significantly reduced.

As a result, VPS hosting is a versatile, flexible hosting option. It’s particularly well-suited to experienced users who can thoroughly enjoy the freedom that it provides.

The Cons of VPS Hosting

Before you get too excited about VPS hosting, it’s vital to consider the main pitfalls of this option:

Challenging for Beginners

VPS hosting generally isn’t a great fit for beginners. In fact, even experienced users might struggle with some of the tasks. For example, you’ll need to be able to administer a server, and build and manage the application you want to host.

Requires More Time

While you might be able to establish your website fairly quickly, certain tasks like website maintenance and security management can require significant time and effort.

Responsibility

Not all of your VPS options will be fully managed. Being solely responsible for your site with no experts to help you out can be daunting.

Cost

Renting a VPS can be expensive because providers can’t put as many customers on one server. However, prices differ drastically depending on the setup, bandwidth, and hardware options. While some managed hosting plans might seem pricey, bear in mind that you get access to a ton of additional services and expert support.

This is one of the reasons we offer managed VPS hosting:

VPS hosting

Managed VPS hosting aims to address the main issues of unmanaged hosting. You can rent a VPS server while accessing many other useful services that make this a more manageable and beginner-friendly alternative.

Of course, you can still enjoy blazing performance by configuring your server resources. However, you can also benefit from one-click SSL installation, unlimited domains, and automatic software updates. As a result, you can combine the convenience of managed hosting packages with the freedom that VPS provides.

Take Charge with Flexible VPS Hosting

Here’s how DreamHost’s VPS offering stands apart: 24/7 customer support, an intuitive panel, scalable RAM, unlimited bandwidth, unlimited hosting domains, and SSD storage.

VPS hosting provider

VPS vs. Managed WordPress Hosting

Here is a quick overview of the differences between VPS vs. managed WordPress hosting:

Managed WordPress Hosting VPS Hosting
Beginner-friendly Yes No
Requires more time No Yes
Ultimate freedom No Yes
Suitable for WordPress Yes Yes
Secure Yes Yes
Automated features Yes No

 

If you have the technical know-how and don’t mind spending more time and effort on your site, VPS hosting is an excellent choice. What’s more, you can enjoy complete control and flexibility over your site, which makes this setup great for creating custom solutions.

However, for beginners or businesses that don’t have extra time to invest in site management, managed hosting is the simpler option. Plus, you will benefit from additional services and expert support to troubleshoot issues quickly.

Choose the Right Hosting Solution for Your Website

It can be difficult to choose a web hosting solution. However, this process is easier when you know what to look for. While VPS hosting is a great option for users with technical skills, managed WordPress hosting is an excellent choice for beginners.

You can enjoy complete freedom, control, and flexibility with a VPS. However, it can be more demanding being solely responsible for your site. On the other hand, managed WordPress hosting takes care of all the technical aspects of running a website, freeing up time to invest in your business.

At DreamHost, we offer a range of solutions to suit all kinds of users, from managed WordPress hosting to managed VPS hosting. Whichever option you choose, you will enjoy 24/7 support, fast speeds, and unmetered bandwidth. Check out our plans to get started!

The post Managed WordPress Hosting vs VPS (Buyer’s Guide) appeared first on Website Guides, Tips & Knowledge.



source https://www.dreamhost.com/blog/managed-wordpress-vs-vps/

Friday 28 October 2022

Beginner’s Guide to the WordPress .htaccess File

Keeping your site safe should be a top priority for every administrator. WordPress is a secure platform out of the box, but that doesn’t mean it’s impervious to attacks. Fortunately, even if you aren’t a security expert, you can use a file called .htaccess to harden your site’s security policies.

.htaccess is a configuration file for the Apache web server, which serves many WordPress sites. It’s a powerful tool that helps safeguard your site and boost its performance through some minor tweaks to its code. By editing this file, you can ban users, create redirects, prevent attacks, and even deny access to specific parts of your site.

An Introduction to the .htaccess File

.htaccess is short for “HyperText Access.” It’s a configuration file that determines how Apache-based servers interact with your site. In simpler terms, .htaccess controls how files in a directory can be accessed. You can think of it as a guard for your site because it decides who to let in and what they’re allowed to do.

By default, an .htaccess file is typically included in your WordPress installation. The main purpose of this file is to improve security and performance. Plus, it also enables you to override your web server’s settings.

You’ll most likely find your .htaccess file in your site’s root directory. Since .htaccess applies to both its own directory and any subdirectories within that main folder, it impacts your entire WordPress site.

It’s also worth noting that the .htaccess file does not have a file extension. The period at the start simply makes sure the file remains hidden.

How to Edit Your WordPress .htaccess File

Editing the .htaccess file is, in practice, as simple as editing any other text file. However, because this is a core file, making changes to it can have unintended consequences.

For this reason, it’s vitally important that you back up your site before you begin, regardless of whether you’re a beginner or an experienced developer.

When you’re ready to edit your .htaccess file, you can access it using Secure File Transfer Protocol (SFTP) or Secure Shell (SSH). You will find .htaccess in your site’s root directory:

WordPress .htaccess file

Open the file using your preferred text editor, such as TextEdit or Notepad. If the file hasn’t been edited before, you’ll see the following default information:

WordPress .htaccess file

It’s important not to add or change anything between the # BEGIN and # END tags. Instead, all new code should be added after this block.

At this point, all you need to do is add your code and save the file. When you’re including multiple new functions, it’s best to save and test each one separately. If an error occurs, this will make it much easier to troubleshoot which change caused the problem.

While almost all WordPress installations will already contain an .htaccess file, in some cases, you may need to create one. You can do this using a text editor of your choice, as long as you save it with the right file name: .htaccess with no extension.

It’s also important to configure the file’s permission settings correctly. You can then upload .htaccess to your site’s root directory.

9 Things You Can Do With Your WordPress .htaccess File

Now that you’re familiar with the .htaccess file, it’s time to get up close and personal. We’re going to introduce a number of ways you can easily boost your site’s security and performance by editing this file.

Simply use the code snippets we’ve provided below, and remember to create a backup before you start!

1. Deny Access to Parts of Your Site

One of the most useful things you can do with .htaccess is deny access to certain pages and files. There are a few files you should consider hiding in this way for security reasons, such as your wp-config.php file.

You can do this by adding the following code, which will cause a 404 error to appear if anybody attempts to view the file:

<Files ~ "/wp-config.php">
Order Allow,Deny
Deny from All
</Files>

In cases where sensitive data should be hidden, it can be useful to restrict access to the corresponding directory. Since many WordPress sites use the same folder structure, this setup can leave your site vulnerable. If you add the following line, it will disable the default directory listing functionality:

Options -Indexes

This will stop users and robots from viewing your folder structure. If anybody tries to access it, they’ll be shown a 403 error page instead.

2. Redirect and Rewrite URLs

Creating redirects enables you to automatically send users to a specific page. Redirects can be particularly useful if a page has moved or been deleted, and you want users who attempt to access that page to be taken somewhere else.

You can accomplish this with a plugin such as Redirection, but it’s also possible to do it by editing the .htaccess file. To create a redirect, use the following code:

Redirect /oldfile.html http://www.example.com/newfile.html

You can probably see what’s going on here. The first part is the path to the old file, while the second part is the URL you want visitors to be redirected to.

Get Content Delivered Straight to Your Inbox

Subscribe to our blog and receive great content just like this delivered straight to your inbox.

3. Force Your Site to Load Securely With HTTPS

<style>.embed-container { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; } .embed-container iframe, .embed-container object, .embed-container embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }</style><div class=’embed-container’><iframe src=’https://www.youtube.com/embed/QeicRf_Ri3Y’ frameborder=’0′ allowfullscreen></iframe></div>

If you have added an SSL certificate to your domain, such as DreamHost’s free Let’s Encrypt certificate, it’s a good idea to force your site to load using HTTPS. This will ensure that your site is safer for both you and your visitors.

You can make it happen by adding the following code:

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Your site will now automatically redirect any HTTP requests and direct them to use HTTPS instead. For example, if a user tries to access http://www.example.com, they will be automatically redirected to https://www.example.com.

4. Change Caching Settings

Browser caching is a process where certain website files are temporarily saved on a visitor’s local device to enable pages to load faster. Using .htaccess, you can change the amount of time that your files are stored in the browser cache until they are updated with new versions.

There are a few different ways to do this, but for this example, we’ll use a function called mod_headers. The following code will change the maximum caching time for all jpg, jpeg, png, and gif files:

<ifModule mod_headers.c>
<filesMatch "\\.(jpg|jpeg|png|gif)$">
Header set Cache-Control "max-age=2592000, public"
</filesMatch>

We’ve set the maximum time to 2,592,000 seconds, which equates to 30 days. You can change this amount if you want, as well as the file extensions that will be affected. If you want to add different settings for different extensions, simply add more mod_header functions.

5. Prevent Certain Script Injection Attacks

Script injection (or ‘code injection’) attacks attempt to change how a site or application executes by adding invalid code. For example, someone might add a script to a text field on your site and then submit it, which could cause your site to actually run the script.

You can add the following code to protect against certain types of script injection:

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{QUERY_STRING} (\<|%3C).*script.*(\>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]
RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})
RewriteRule ^(.*)$ index.php [F,L]

Your site should now be able to detect and stop script injection attempts and redirect the culprit to your index.php page.

However, it’s important to note that this example will not protect against all types of injection attacks. While this particular code can certainly be useful, you should not use it as your only protection against this type of attack.

6. Stop Username Enumeration Attacks

Username enumeration is a process where usernames from your site are harvested by looking at each user’s author page. This is particularly problematic if someone manages to find your admin username, which makes it much easier for bots to gain access to your site.

You can help prevent username enumeration by adding the following code:

RewriteCond %{REQUEST_URI} !^/wp-admin [NC]
RewriteCond %{QUERY_STRING} author=\d
RewriteRule .* - [R=403,L]

This will stop certain attempts to enumerate usernames and throw up a 403 error page instead. Bear in mind that this will not prevent all enumeration, and you should test your security thoroughly. We also recommend strengthening your login page further by implementing Multifactor Authentication.

7. Prevent Image Hotlinking

Image hotlinking is a common problem that happens when images on your server are being displayed on another site. You can stop this by adding the following code to .htaccess:

RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https://(www\.)?example.com/.*$ [NC]
RewriteRule \.(png|gif|jpg|jpeg)$ https://www.example.com/wp-content/uploads/hotlink.gif [R,L]

Replace example.com with your own domain, and this code will prevent images from loading on all other sites. Instead, the picture you specify on the last line will load. You can use this to send an alternative image to sites that try to display graphics from your server.

Beware that this may cause issues when you might want images to appear externally, such as on search engines. You might also consider linking to a script instead of a static image, then respond with a watermarked image or an image containing an ad.

8. Control Your File Extensions

By using .htaccess, you can control how files of different extensions are loaded by your site. There’s a lot you can do with this feature, such as running files as PHP, but we’re just going to look at a basic example for now.

The following code will remove the file extension from PHP files when they’re loaded. You can use this with any file type, as long as you replace all instances of “php” with the extension you want:

RewriteEngine On
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.*index\ HTTP/
RewriteRule ^(.*)index$ http://example.com/$1 [L,R=301]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/$ http://example.com/$1 [L,R=301]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(.+)\.php\ HTTP/
RewriteRule ^(.+)\.php$ http://example.com/$1 [L,R=301]
RewriteRule ^([a-z]+)$ /$1.php [L]

This will cause all PHP files to load without displaying their extension in the URL. For example, the index.php file will appear as just index.

9. Force Files to Download

Finally, when a file is requested on your site, the default behavior is to display it in the browser. For example, if you’re hosting an audio file, it will start to play in the browser rather than being saved to the visitor’s computer.

You can change this by forcing the site to download the file instead. This can be done with the following code:

AddType application/octet-stream mp3

In this example, we’ve used mp3 files, but you can use the same function for txt, mov, or any other relevant extension.

Improve Your Site’s Security and Performance

The .htaccess file provides flexibility for controlling how your web server behaves. You can also use it to increase your site’s performance and get more control over exactly who can access what information.

With .htaccess, you can deny access to particular parts of your website. Additionally, it allows you to redirect URLs, force your site to load over HTTPS, and prevent some script injection attacks.

Editing your .htaccess file is just one way to improve your site’s security. Choosing a secure WordPress hosting provider is another. Check out our DreamPress managed hosting plans to see how we can boost your website’s security and performance!

Do More with DreamPress

DreamPress Plus and Pro users get access to Jetpack Professional (and 200+ premium themes) at no added cost!

Managed WordPress Hosting - DreamPress

The post Beginner’s Guide to the WordPress .htaccess File appeared first on Website Guides, Tips & Knowledge.



source https://www.dreamhost.com/blog/guide-to-wp-and-htaccess/

Thursday 27 October 2022

How to Secure Your WordPress Site (25 Hardening Tips)

WordPress is an excellent, secure platform out of the box, but there’s certainly more you can (and should!) do to keep your site safe from malicious intent. Many of these security enhancements are easy to implement and can be performed manually in mere minutes. Others simply require installing a particular plugin.

In this article, I’ll guide you through 25 different strategies for upping the defenses on your WordPress fortress. But first, let’s go a little more into the weeds on why website security should matter to you.

Why WordPress Security is So Important

WordPress

If you’re looking to create a secure site, choosing WordPress as your platform is an excellent way to start. It’s not only a flexible, powerful platform for building websites — it’s also remarkably secure out of the box.

That’s because WordPress developers care about security and are dedicated to “hardening” the core platform as much as possible. Plus, they frequently release security-focused updates and patches, which will be automatically downloaded and installed on your site. This means your site will be well-equipped to deal with any new threats that pop up.

Of course, no platform can be 100% secure. Hackers are hard at work trying to find their way into even the most well-protected sites (if only they’d use their powers for good, amirite?) And since WordPress powers more than 30% of the web, it’s popular enough to be a constant target.

It should go without saying, but if baddies do manage to break into your site, they can cause a lot of damage.

For example, they can steal or otherwise compromise sensitive information, install malware, make changes to your site to suit their needs, or even bring it down entirely. This is harmful to both you and your users, and if you’re running a business,  it can mean lost customers and revenue.

It’s vitally important to take additional steps to secure your WordPress website. You’ll want to put just as much time and effort into this endeavor as you spent designing your site in the first place (if not more). Fortunately for you, dear reader, there are lots of simple, quick ways to improve your site’s security, as well as some more complex techniques you may want to employ.

25 WordPress Security Tips

Hopefully, I’ve convinced you about the importance of maintaining a secure WordPress website. If not, I’m going to have to re-enroll in Persuasive Writing 101. Please don’t make me do that.

Throughout the rest of this article, I’ll introduce 25 handy strategies for making your site safer and reducing the chances of it being compromised. Plus, I’ll point you in the right direction to get started with each technique.

You don’t have to implement every suggestion on this list — although you certainly can — but the more steps you take to secure your site, the lower your chances of encountering a disaster down the road.

Use a Quality Host

You can think of your web host as your website’s street on the Internet — it’s the place where your site “lives.”

Like a good school district matters to your kid’s future (so they say; I turned out fine), the quality of your website’s home base counts in a lot of big ways.

A solid hosting provider can impact how well your site performs, how reliable it is, how large it can grow, and even how highly it ranks in search engines. The best hosts offer many useful features, excellent support, and a service tailored to your chosen platform.

As you’ve probably already guessed, your web host can also have a significant impact on your site’s security. There are several security benefits to choosing a solid hosting service.

How Web Hosting Can Improve WordPress Security

  • A quality host will constantly update its service, software, and tools to respond to the latest threats and eliminate potential security breaches.
  • Web hosts often offer various targeted security features, such as SSL/TLS certificates and DDoS protection. You should also get access to a Web Application Firewall (WAF), which will help monitor and block serious threats to your site.
  • Your web host will most likely provide a way to back up your site (in some cases, even carrying it out for you), so if you’re hacked, you can easily revert to a stable, previous version.
  • If your host offers reliable, 24/7 support, you’ll always have someone to help you out if you do run into a security-related issue.

 

This list should give you a good starting point to work from when looking for a host for your new site, or even if you’re thinking about changing hosts. You’ll want to find one that offers all of the features and functionality you’ll need, plus has a reputation for reliability and excellent performance.

DreamPress is a managed WordPress hosting service that’s fast, reliable, scalable, and, of course, secure. DreamPress includes a pre-installed SSL/TSL certificate and provides a dedicated WAF designed with rules built to protect WordPress sites and block hacking attempts. You’ll also get automated backups, 24/7 support from WordPress experts, and Jetpack Premium — a plugin that can add many additional security features to your site — at no additional cost.

With DreamPress, you’ll be able to rest easy knowing that your site is protected. Our hosting service even takes care of many of the following security-enhancing steps for you — although we still encourage you to read on to learn what extra measures you can take.

Private Domain Registration

To register a domain, you’re asked to provide your name, address, and phone number. This information is used to track ownership of domain names and is available online with a quick search on the WHOIS directory.

While keeping track of this information is vital to the health of the internet, it’s reasonable not to want your personal information online. This is where Private Registration enters the story. When you register a domain with DreamHost (or another secure hosting platform, I guess), you have the option to substitute your personal information with the relevant data from the hosting platform– So, looking up your domain on WHOIS would show DreamHost’s address and contact information. You can even enable this security feature after your domain has already been registered!

Switch Your Site to HTTPS

Let’s talk more about an SSL/TLS certificate. This enables you to switch your site to HyperText Transfer Protocol Secure (HTTPS) — a more secure version of HTTP. These are important security concepts to understand but simple to grasp, even if you’ve never heard of them before.

HTTP is the protocol that transfers data between your website and any browser trying to access it. When a visitor clicks on your home page, all of your content, media, and website code are sent through this protocol to the visitor’s location.

While this is necessary, of course, it does introduce some potential security issues. Baddies can try to intercept the data while it is in transit and use it for their own nefarious purposes.

HTTPS solves this problem! It does the same thing as HTTP but also encrypts your site’s data while it’s traveling from one point to another, so it can’t be easily accessed.

Initially, HTTPS was used mainly for sites handling sensitive customer information, such as credit card details. However, it’s becoming increasingly common for all sites, and big names such as WordPress and Google have been pushing for its widespread implementation.

How to Switch to HTTPS

To switch your site over to HTTPS, you’ll first need an SSL/TLS certificate. This communicates to browsers that your site is legitimate and its data is properly encrypted.

You can also get one for free from certain sites, such as Let’s Encrypt.

 

A quality host will typically provide an SSL/TLS certificate as part of your hosting package. In fact, at DreamHost, we offer Let’s Encrypt certificates for free with all of our hosting plans!

Once you have an SSL/TLS certificate installed on your site, you’ll simply need to implement HTTPS. Your host may take care of this for you, although it’s also fairly easy to do yourself. If you’ve chosen to go with DreamPress, the stretch limo of hosting, your site will be created using HTTPS from the start. Roll out!

Get Content Delivered Straight to Your Inbox

Subscribe to our blog and receive great content just like this delivered straight to your inbox.

Change the Admin Username

When you first create your website, all shiny and new, you’re given a User Profile. At any time, you can go back and change your Nickname or fill in your Full Name, but to change your username is an entirely different story. To change your username you will need to create a whole new user and grant that account the administrator role. The drawback? You need to use a different email address than the one used by your current account.

After creation, you can alter your username by creating a new user, giving it the administrator role and attributing all your content to it, and then deleting your original account. When your previous username has been deleted, you can change the email address of your new account if you desire.

the WordPress login screen

Create a Secure Password

Folks, it’s really important to select your login credentials carefully. Like really, really important!

Why? This makes it harder for a sketchy weirdo to break into your site. You probably have plenty of experience choosing strong usernames and passwords for other accounts across the web — doing the same for your WordPress website is a big deal.

When you create your site, you’ll be given the opportunity to create a login username and password. The username will default to admin, although you can change it if you’d like (and probably should). But since there are various ways for people to find out what your WordPress username is, you can stick with the default option if you want to.

Your password, however, is crucially important, and you’ll want to choose a strong one. There’s recently been a U-turn of sorts on how to choose a strong password, with a recommendation of a simple four-word phrase trumping the classic mixture of random letters, numbers, and symbols. It’s a method that has been popular in some circles for a while.

If all the talk of choosing a password makes your head spin, we recommend sticking with WordPress’ own password generator as it automatically generates an (almost) ironclad password directly within the WordPress back end. Just be sure to record your credentials somewhere safe, like an encrypted password manager, so you don’t forget them.

For your password, you can simply go to Users > All Users from your WordPress admin dashboard, click on your username and enter a new password on the Edit User screen.

Enable a Web Application Firewall

​​

 

You’re probably familiar with the concept of a firewall — a program that helps to block all sorts of unwanted attacks. Most likely, you have some kind of firewall on your computer. A Web Application Firewall (WAF) is simply a firewall designed specifically for websites. It can protect servers, specific websites, or entire groups of sites.

A WAF on your WordPress site will function as a barrier between your website and the rest of the web. A firewall monitors incoming activity, detects attacks, malware, and other unwanted events, and blocks anything it considers a risk. #winning

If you’ve opted for our DreamPress package, you can relax; you won’t need an additional firewall. DreamPress includes a built-in WAF that will monitor your site for threats and block malicious users and programs from gaining access. No action required on your part.

DreamHost also offers DreamShield, our in-house malware scanning service. When you enable DreamShield on your hosting account, we’ll scan your site weekly for malicious code. If we find anything suspicious, you’ll be notified immediately via email.

Implement Two-Factor Authentication 

Before we move on, there’s one more technique to address: two-factor authentication (which also goes by two-step authentication and a variety of other, similar names). The term refers to the two-step process you’ll need to follow when logging into your site. This takes a little more time on your end but goes a long way towards keeping hackers out.

Two-factor authentication involves using a smartphone or other device to verify your login. First, you’ll visit your WordPress site and enter your username and password as usual. A unique code will then be sent to your mobile device, which you’ll need to provide to complete logging in. This enables you to prove your identity by showing you have access to something solely yours — such as a particular phone or tablet.

As with many WordPress features, two-factor authentication is easy to add with a dedicated plugin. Two Factor Authentication is a solid choice — it’s created by reliable developers, compatible with Google Authenticator, and will enable you to add this functionality to your site without fuss.

Another choice is the Two-Factor plugin, which is well known for its reliability and was built mainly by core WordPress developers. As with any plugin in this category, the learning curve is a little steep, but it will get the job done and is very secure. If you’re willing to spend a little money, you can also check out Jetpack’s Clef-like premium solution.

Whatever route you choose, make sure to plan ahead with your team if relevant, since you’ll need to gather their phone numbers and other information to get started. With that, your login page is now secured and ready to go.

Be Mindful When Adding New Plugins and Themes

The ready availability of themes and plugins is one of the best things about using WordPress. With these handy tools, you can make your site look just right and add nearly any feature or functionality you can think of.

Not all plugins and themes are created equally, though.

Developers who aren’t careful or don’t have the right level of experience can create plugins that are unreliable or insecure — or, just downright sucky. They might use poor coding practices that leave holes hackers can easily exploit or unknowingly interfere with crucial functionality.

This all means you need to be very careful about the themes and plugins you choose to add to your site. Each one should be vetted to ensure it’s a solid option that won’t hurt your site or cause problems. There are many elements to keep in mind, but the following advice will help you select quality tools:

  • Read reviews. Check user ratings and reviews to learn whether other people have had a good experience with the plugin or theme in question.
  • Developer support. Take a look at how recently the plugin or theme has been updated. If it’s been longer than six months, chances are it isn’t as secure as it could be.
  • Easy does it. Install new plugins and themes one at a time, so if anything goes wrong, you’ll know what the cause was. Also, be sure to back up your site before adding anything to it.
  • Vetted sources. Get your plugins and themes from trustworthy sources, such as the WordPress.org Theme and Plugin Directories, ThemeForest and CodeCanyon, and reliable developer websites.

Update Often 

Your work isn’t done once you’ve installed the plugins and themes you want for your site.

You’ll also need to keep them up to date to ensure they work well together and are secured against the latest threats. Fortunately, this is quite easy — you’ll simply need to go to your WordPress dashboard, look for the red notifications telling you there are themes and/or plugins with available updates, and click on update now next to each one.

keep WordPress secure by regularly updating plugins

You can also update your plugins in a batch by selecting all of them and then hitting the update button, either here or in the WordPress panel. This is a quicker option, but keep in mind, updating all of them at once could make it more difficult to diagnose any problems that arise as a result of the updates. If you’re making sure to only choose reliable plugins and themes, however, this shouldn’t be a problem.

Before we move on, it’s worth mentioning that you should also keep WordPress itself up to date. Smaller patches and security updates will be added automatically, but you may need to implement major updates on your own (again, this is very simple to do). This probably goes without saying at this point, but DreamHost handles these updates for you, so you won’t need to worry.

Remember: leaving WordPress or any of your themes and plugins out of date is a risk you don’t want to take.

Configure File Permissions 

Let’s talk technical for a moment.

A lot of the information, data, and content on your WordPress site is stored in a series of folders and files. These are organized into a hierarchical structure, and each one is given a permissions level. The permissions on a WordPress file or folder determine who can view and edit it and may be set to allow access to anyone, only to you, or almost anything in between.

File permissions are represented by a three-digit number in WordPress, and each digit has a meaning. The first digit stands for an individual user (the site’s owner), the second digit for the group (for example, members of your site), and the third for everyone in the world. The number itself means that the user, group, or world:

  • 0: Has no access to the file.
  • 1: Can only execute the file.
  • 2: Can edit the file.
  • 3: Can edit and execute the file.
  • 4: Can read the file.
  • 5: Can read and execute the file.
  • 6: Can read and edit the file.
  • 7: Can read, edit, and execute the file.

So if a file is given a permissions level of 640, for example, it means the primary user can read and edit the file, the group can read the file but not edit it, and everyone else cannot access it. This may seem overly complicated, but it’s important to ensure that each person only has the level of access to your site’s files and folders you want them to have.

WordPress recommends setting folders to a permissions level of 755 and files to 644. You’re pretty safe sticking to these guidelines, although you can set up any combination you’d like. Just remember that it’s best not to give anyone more access than they absolutely need, especially to core files.

You’ll also want to keep in mind that the ideal permissions settings will depend somewhat on your hosting service, so you may want to find out what your host recommends.

Note: You should be very careful when making changes to your permissions levels — choosing the wrong values (like the dreaded 777) can make your site inaccessible.

Keep WordPress Users to a Minimum

If you’re running your WordPress site solo, you don’t need to worry about this step. Just don’t give anyone else an account on your site, and you’ll be the only person who can make changes.

However, many humans like other people and do eventually add more than one user to their website. You may want to let other authors contribute content, or you might need people to help edit that content and manage your site. It’s even likely you’ll find yourself with an entire team of users who’ll regularly access your WordPress site and make their own changes.

This can be beneficial in many ways and is sometimes even necessary. However, it’s also a potential security risk.

The more people you let into your site, the higher the chance that someone will make a fat-finger mistake or that a user will cause problems just to be a putz. For this reason, it’s smart to keep the user count on your site as low as possible while not hampering its ability to grow. In particular, try to limit the number of administrators and other user roles with high privileges.

Here are a few more suggestions:

  • Limit each user to only what permissions are necessary for them to do their job.
  • Encourage users to use strong passwords (remember No. 3?).
  • Try to stick with one administrator, if possible, and a small group of editors.
  • Give users who have left the site or no longer need access the boot.
  • Consider downloading a plugin, such as Members, which provides a user interface for WordPress’ role and capabilities system.
content permissions settings in WordPress

Log Out Idle Users  

It’s happened to all of us– we’re browsing on the computer when something distracts us IRL (in real life). The dog barks, the doorbell rings, and after we stand up and take care of whatever got our attention, there’s something else to do. And again, and again, and then it’s been 3 hours since you were at your computer, and your cat has typed “fdhhhhhhhhhhhhhhhhhhh” in your chat.

Of course, mittens typing her feelings on discord is actually the least malicious thing that could happen. Leaving a computer unlocked means that someone could take over their session and make changes to their account or your website.

While user awareness is always a great solution, sometimes you just have to say “There’s a plugin for that!” In this case, the Inactive Logout plugin.

use session timeouts to keep WordPress secure

Once you install and activate the plugin, visit Settings >> Inactive Logout page. Here you can configure when the timeout activates, and add a message to be displayed during inactivity.

Whether you choose to grab the plugin or not, remember that practice makes perfect, and remind anyone with access to your site that they should log out or lock their computer when they walk away.

Limit Login Attempts 

Forgetting your password is a universal experience. It can take 2 or 3 attempts before we angrily try to reset our password and get “error: password must not have been used previously.”

resetting your password in WordPress

But I digress. WordPress allows an unlimited amount of guesses, which means that brute force attacks, or attacks where a hacker tries any number of passwords, are one of the most common ways hackers gain access to private accounts. With no limit on login attempts, a hacker could try every password in the book with no consequences.

To set a limit to the amount of login attempts a user can make, first check your Web Access Firewall (WAF) mentioned in #6. If your firewall is already set up, there will already be a limit in place.

But, never forget, there’s a plugin for that! In fact, there are several.

Both Login Lockdown and Cerber Limit Login Attempts record the IP Address and Time Stamp of each failed login attempt, and allows you to set how many failed attempts are allowed in a certain span of time, as well as how long that IP address should be locked out for. Both are free, however Login Lockdown is simpler to navigate, limiting your options to only what a beginner might need. If you require a more robust system, Cerber Limit Login Attempts is the way to go, allowing not only IP white/blacklisting, but also notifying admins if a certain number of lockouts is reached.

 

Track Your Admin Area Activity 

If you’ve got multiple users, it can be a good idea to keep tabs on what they’re all doing on the site. Tracking activity in your WordPress admin area will help you spot when other users are doing things they shouldn’t and can indicate whether unauthorized users have gained access.

When a weird change has been made or something suspicious is installed, you’ll want to be able to find out who was behind the activity. Plugins got you covered.

Most larger security plugins don’t provide this functionality out of the box, so you’ll want to find a dedicated solution. If you’d like to take a hands-off approach, Simple History lives up to its name by creating a streamlined, easy-to-understand log of important changes and events on your site.

For more involved tracking features, you can also check out WP Security Audit Log, which keeps an eye on just about everything that happens on your site and offers many useful, premium add-ons.

WP Security Update Logs plugin in WordPress

Once you have a suitable plugin installed, it’s a smart idea to check the log periodically for anything out of the ordinary. If something happens on your site that you weren’t expecting or bugs suddenly pop up, look through the most recent activity.

Utilize CAPTCHA

Junkmail! Spam! Whatever you call it, it shows up in our comments or our inboxes sooner or later. Usually spam is harmless commercials trying to get your attention– The danger comes from junk mail that is hiding phishing links or malicious software. So what’s the best way to get those cheesy advertisements out of your comment section, and make sure that any form results you collect are legitimate? It sure would be nice if we had some sort of Completely Automated Public Turing test to tell Computers and Humans Apart (aka: our friend, CAPTCHA).

CAPTCHA works by asking the user to do something that software cannot do. You may be asked to check a box, click all the images with a boat in them (oh, we love those don’t we?), or typing in some wobbly letters. When the user does the task correctly, the system says “oh, this isn’t a spambot!” and lets them pass.

Captcha to improve WordPress security

There are a few different plugins that allow you to add a CAPTCHA to certain pages in your website, the most widely talked about would be reCaptcha by BestWebSoft. With several versions of CAPTCHA available through the plugin, frequent updates, and the plugin available in 12 languages, it’s truly the whole package.

Another option is CAPTCHA 4WP By WP White Security. CAPTCHA 4WP allows you to add CAPTCHA not just to WordPress forms, but also to eCommerce pages and other third party plugins.

As the BestWebSoft reCAPTCHA page says “easy for people and hard for bots.”

Backup Your Site Regularly 

I’d be lying if I said there was a magic solution for protecting your website from all threats. Even if you implement every suggestion on this list, there’s still a chance you may experience a security breach on your site.

Hackers are good at what they do. You’ve just got to beat them at their game.

A comprehensive security plan means preparing for what you’ll do if the worst happens, even while you’re trying to ensure it never does.

Backing up your site on a regular basis is the simplest and best way to safeguard it in the event of a disaster. If you have a recent backup handy, you can restore your site to the way it was before it was hacked or otherwise harmed. This will help you fix the issue and move on as quickly as possible.

 

Of course, you’ll want to be smart about the way you create and use your backups. The following tips are a good start:

Keep more than one backup. A good rule of thumb is to have at least three recent backups on hand at all times since it’s possible your most recent backup could have issues you haven’t yet noticed.

Save your backups in multiple external locations, such as cloud storage and physical hard drives.

Set up and stick to a consistent backup schedule. The frequency and timing are up to you, although there are plenty of solid recommendations you can follow.

In addition to your regular backup schedule, it’s always smart to create an extra backup of your site before making any changes to it. So (nudge, nudge) before implementing any of these security-boosting techniques, make sure you have a recent backup ready to go.

Password Protect Your Login Page 

The login page is the most likely way for hackers to try to access your website, and if you’re hosting content that perhaps not everyone needs to see, password protection is still the best way to go.

As a simple solution, for blog posts or an About Me section, you can add password protection by going into pages >> all posts option within your WordPress account. Once you hit “edit” you’ll see the option to change the visibility to “Password Protected”. Just publish, and badabing-badaboom, that page is locked up tight!

There are other methods to lock different areas of your website. A few options can be a bit technical, but are still worth learning. For example, you can create an htaccess file, and add a password prompt to your login page! A login for your login! What will they think of next?

Hide Your Login Page

Adding password protection to your login page is great, but what if hackers couldn’t even find your login page? As we’ve stated before, defaults can be our greatest weakness, and changing your wp-admin and wp-login pages are too easy not to do!

There are several plugins that offer this service and will even redirect the default login page to another page of your choosing. It’s possible to find plugins that offer this as part of a large package (Defender also includes a malware scanner and firewall) but if you’re looking for something simple, there’s something for you as well (WPS Hide Login hides your login and that’s it. There are other extensions available, but this keeps things simple). Just don’t forget, you may need to bookmark your login page since it won’t be the default anymore.

Update PHP 

 

Just like America runs on Donuts (don’t quote us there), WordPress runs on PHP. Updating WordPress isn’t enough to keep your site safe and secure– you need to be sure that you’re using one of the latest versions of PHP as well.

Normally each PHP version is supported for at least 2 years after its release date, so any vulnerabilities are addressed by the engineers who designed the code. When that code goes out of date (or reaches its EOL or “end of life”), it’s time to upgrade, or risk being exposed to security concerns, performance slowdown, and bugs galore!

In November, 2022, PHP 8.2 will be released. To see which version of PHP you’re currently running, login to your WordPress site, and select Tools >> Site Health. Navigate to Info and then Server, and there’s your current PHP version.

Secure Your Database 

Leaving anything at the default settings is a boon for hackers, and by default WordPress uses wp_ as the prefix for All of your related tables. Good news! If you’re using the One-Click Installer there is already a prefix of random letters and numbers. As long as it ends with an underscore, the system is happy. Better News! Even if your WordPress is already installed, it may be eligible for the One-Click Installer as long as the website is fully hosted, and meets a few other guidelines.

This is a big step for security, and breaking something can be as easy as a missing underscore. Luckily, there is a default version of the wp-config.php file available at WordPress Core available, so you can rebuild whether you tried to change the database prefix manually, or with a service like phpMyAdmin.

Add Security Questions 

adding security questions to the WordPress login process

While not the most common solution, security questions give that extra oomph to your security. Depending on the plugin you choose, you may need to choose from already existing security questions, or be able to create your own. This feature often comes bundled with another feature, for example two-factor authentication. Don’t underestimate the abundance of methods available to protect your login page from nefarious actors!

Hide WordPress Version 

We talked about keeping your website up to date, but what if that’s not an option? We know how reluctant people have been with updating Microsoft Windows…

Well, Security through Obscurity– if they can’t find it, they can’t hack it! Hide which version of WordPress you’re using, or hide that you’re using WordPress altogether. You can hide your WordPress information by altering the header code. While you can go into your theme settings and edit the display information there, those snippets of code will only return during the next theme update.

But, of course, there’s a plugin for that. WPCode is a free plugin that allows you to enter a variety of code snippets, including one for removing the version number, no matter how many times that pesky theme tries to write it back in.

Prevent Hotlinking 

Hotlinking is the act of stealing bandwidth by using files hosted on one site, and linking them to another. For example, let’s say someone draws a pretty clever comic, and perhaps some other website wants to feature that content without permission. They would hotlink those comics– instead of hosting them from their own servers, they would just link to them. This costs the original website more bandwidth, and therefore more money.

To prevent hotlinking, you can choose to reject certain domains, allow only certain domains, or remove the ability to hotlink all together all by making a few changes to your htaccess file. You can even include a snippet in your .htaccess file that routes all hotlinking attempts to a page or image of your choice– perhaps one that specifically says “Stop Hotlinking, 2022!”

DDoS Protection ( Disable XML RPC )  

A Distributed Denial of Service attack (or DDoS), is when a hacker uses multiple systems to send a huge volume of data and overwhelm their target. This can slow down and crash their target – imagine a huge traffic jam for your website where no legitimate traffic could get in.

We know that patience on the internet is hard to come by, with the average user waiting only 3 seconds for a page to load before clicking away, so the sooner you can identify and resolve an attack on your website, the better.

While preventing a DDoS attack may seem daunting, one of the first steps you can take is to remove (or at least disabe) any old or unutilized plugins. Plugins are incredibly useful, but by increasing functionality, they also have access to your website that can be exploited. For once, downloading more plugins is not the answer!

You also may be wondering what this XML-RPC is. Well, specifically, it allows WordPress access through the app on your mobile device. If you’re not using your smartphone to make changes to your WordPress website, then you likely don’t need this feature enabled. Turning it off involves adding a quick snippet of code to your htaccess file, and you’ll be all the safer for it.

Malware Scanning 

Unfortunately, there is software out there that is more covert than your average pop-up virus. Malware (short for malicious software) hides in what appears to be decent applications so that the user doesn’t know their computer or website has been infected.

Malware scanning is an important defense– It works by deep scanning the computer and using anti-malware software to identify and isolate suspicious files until you decide if they need to be removed. If a threat is detected, a good malware scanner will delete any trace of it from your computer ASAP. Luckily, several firewall plugins come with malware scanning built in– so make sure to check your current security plugins to see what they offer.

If you have DreamHost as your hosting platform, you can activate DreamShield to handle malware scanning for you on a weekly basis.

DreamShield malware removal tool by DreamHost

WordPress Security: Locking It Up 

If your website is hacked, you’ll spend hours (perhaps even days) trying to repair the damage. You may permanently lose data or see your personal information compromised — or worse, your clients’ data.

That’s why you’ve got to put a whole lot of time and energy into making sure that this situation never occurs. Otherwise, you’re likely to lose valuable business and precious time.

These 25 WordPress security tips should help. Some are simple tweaks. Others affect your entire site, such as switching to HTTPS or adding an SSL certificate. Of course, you’ll also want to make sure your site runs on a secured WordPress host.

Our DreamPress hosting (with free WordPress migration) is specifically designed for the WordPress environment. Plus, if you ever do encounter a security issue, we’ve got you covered with automatic daily backups, a weekly malware scan, and our support team of WordPress experts!

Smarter Security with DreamPress

DreamPress' automatic updates, caching, and strong security defenses take WordPress management off your hands so you can focus on your website.

Managed WordPress Hosting - DreamPress

The post How to Secure Your WordPress Site (25 Hardening Tips) appeared first on Website Guides, Tips & Knowledge.



source https://www.dreamhost.com/blog/secure-your-wordpress-website/

Tuesday 25 October 2022

Everything You Need to Know About the WordPress functions.php File

To get involved in WordPress development, you’ll first need to understand how the platform’s most important files work. WordPress makes it pretty easy to tinker with your site. However, it can be difficult to know where to start — or predict what your changes will actually do.

A perfect place to learn is the functions.php file, which is also known as the functions file. This is a common location for making changes and adding code to WordPress. By editing this file, you can accomplish several useful things, such as adding Google Analytics to your site, creating custom menus, or displaying a post’s estimated reading time.

What Is the functions.php File?

The WordPress functions.php file comes with all free and premium WordPress themes. To the untrained eye, it may not look like much, but the functions file is a powerful tool that enables you to do a lot of interesting things:

WordPress functions.php

The WordPress Codex describes the functions file like this:

“You can use it to call functions, both PHP and built-in WordPress, and to define your own functions. You can produce the same results by adding code to a WordPress Plugin or through the WordPress Theme functions file.”

In simple terms, the functions file enables you to add custom code to your site. It lets you create new functions or reference existing ones in customized ways. As the Codex points out, this makes the functions file very similar to a plugin, but there are some differences between the two.

The most important difference is that the functions file belongs to a specific theme. If you were to change themes or update to a newer version, the changes you’ve made would disappear.

For this reason, you should consider creating a child theme and adding the new code to the child’s functions file instead. This way, you can update the parent theme without losing your changes.

Whether you choose to use the functions file or create a plugin is entirely up to you. For now, let’s look at the different ways you can edit your functions file!

How to Edit the Functions File (2 Methods)

Editing your functions file is easy when using a standard text editor, like TextEdit or Notepad. However, before you get started, it is vitally important that you create a backup of your site and save the original, unedited functions.php file. This will enable you to restore your website if something goes wrong during the editing process.

1. Use the WordPress Editor

If you have access to the WordPress admin interface, you can edit the functions file directly from the Theme Editor. Go to Appearance > Editor:

WordPress Theme File Editor

On the right-hand side of the screen, you will see a list of all your theme files. These differ depending on which theme you use, but one of the options should be Theme Functions (functions.php).

Simply click on the file to open it in the editor:

WordPress Theme Editor functions.php file

Now, you can edit the file directly. Don’t forget to click on Update File at the bottom to save your changes when you’re done.

2. Access the File Through FTP

If you are unable to use the admin dashboard or prefer to configure files directly, you can also access the functions file using a Secure File Transfer Protocol (SFTP) client such as FileZilla.

Open your FTP tool and enter your hosting credentials to connect to your site. To find the right file, navigate to wp-content/themes/[the name of your theme]. When you open this folder, you’ll see the functions.php file:

editing the WordPress functions.php file through an FTP client

All you have to do now is to edit it using your preferred text editing software. When you’re done, save the file and overwrite it with the exact same name and extension.

8 Tricks You Can Accomplish With the WordPress Functions File

You should now be ready to start editing your functions file. To get you started, we’ll look at some changes that you can make. All you need to do is copy the provided code snippets and paste them on a new line at the very bottom of your functions file (don’t forget to save it!).

1. Add Google Analytics to Your Site

There are several ways of integrating Google Analytics with your WordPress site. One of them is by adding your credentials directly to the functions file. This method will insert the tracking code into your site’s header, ensuring that every visit is properly recorded.

Start by pasting the following code at the bottom of your functions file:

<?php

add_action('wp_head', 'wpb_add_googleanalytics');

function wpb_add_googleanalytics() { ?>

// Replace this line with your Google Analytics Tracking ID

<?php } ?>

All you have to do now is to find your Tracking ID and paste it into the line that contains the placeholder text. When you save the functions file, your site will be connected to your Google Analytics account.

Get Content Delivered Straight to Your Inbox

Subscribe to our blog and receive great content just like this delivered straight to your inbox.

2. Change the Default Login Error Message

By default, when somebody makes an unsuccessful login attempt to a WordPress site, they’ll see an error message like this:

WordPress default login error message

Unfortunately, this message is giving potential intruders information about why the attempt didn’t work. A more secure solution is to change this to a generic message instead.

You can do this easily by adding the following code to your functions file:

function no_wordpress_errors(){
return 'Something went wrong!';
}
add_filter( 'login_errors', 'no_wordpress_errors' );

See that Something went wrong! message on the second line? That message will now appear the next time an incorrect login attempt occurs:

WordPress custom login error message

You can change the text to whatever you want, as long as you keep the single quote characters. Try it out with different messages to see how it works.

3. Add the Estimated Reading Time for a Post

This neat trick enables you to calculate and display the estimated amount of time required to read a post. Your visitors can then get a general idea of the content’s length right away.

To implement this code, you will need to make two separate edits. The first one happens within the functions.php file, where you’ll want to paste the following snippet:

function reading_time() {
$content = get_post_field( 'post_content', $post->ID );
$word_count = str_word_count( strip_tags( $content ) );
$readingtime = ceil($word_count / 200);
if ($readingtime == 1) {
$timer = " minute";
} else {
$timer = " minutes";
}
$totalreadingtime = $readingtime . $timer;
return $totalreadingtime;
}

However, this snippet only performs the calculation. You’ll now need to add the following code wherever you want the results to be displayed:

echo reading_time();

For example, you could add it to the metadata that appears alongside each post. Every theme is constructed differently, but typically you’ll find it in template-parts > post > content.php:

WordPress functions.php estimated reading time

The estimated reading time will now appear in each post’s header alongside the date.

4. Remove the WordPress Version Number

Old versions of WordPress may contain security flaws that malicious hackers and bots can exploit. One way to avoid this risk is to hide which version of WordPress your site uses. This is called security through obscurity.

Before we move on, it’s important to note that obscurity should never be your only security measure. It’s more like adding an extra bulwark to your already secure WordPress fortress.

Hiding your version number only requires adding the following code snippet to the functions file:

remove_action('wp_head', 'wp_generator');

The version number will now be removed from all areas of your site, including its code and your RSS feed.

5. Automatically Update Your Copyright Notice

Updating the year in your copyright notice is one of those little tasks that’s easy to forget. Fortunately, you can edit your functions file to automatically generate the copyright date based on the year when your first post was written.

Paste the following code into your functions file:

function wpb_copyright() {
global $wpdb;
$copyright_dates = $wpdb->get_results("
SELECT
YEAR(min(post_date_gmt)) AS firstdate,
YEAR(max(post_date_gmt)) AS lastdate
FROM
$wpdb->posts
WHERE
post_status = 'publish'
");
$output = '';
if($copyright_dates) {
$copyright = "© " . $copyright_dates[0]->firstdate;
if($copyright_dates[0]->firstdate != $copyright_dates[0]->lastdate) {
$copyright .= '-' . $copyright_dates[0]->lastdate;
}
$output = $copyright;
}
return $output;
}

Then add the following code wherever you want the copyright information to be displayed:

<?php echo wpb_copyright(); ?>

You’ll now see the dynamically updating copyright date on your site.

A dynamically-updating copyright date on a website

In our case, we added the date to the footer.php file, so it would be displayed at the bottom of the page.

6. Add Custom Menus

Most themes have pre-defined navigation menus. However, what if you want to create your own menu and place it wherever you want on your site?

All you need to do is paste this code into your functions file:

function wpb_custom_new_menu() {
register_nav_menu('my-custom-menu',__( 'My Customized Menu' ));
}
add_action( 'init', 'wpb_custom_new_menu' );

You can replace ‘My Customized Menu’ with the name you want to give the menu. If you go to Appearance > Menus in your admin area, you should see the new option listed on the page:

customize your WordPress menus using the functions.php file

You can now add the new menu anywhere on your site.

<?php
wp_nav_menu( array(
'theme_location' => 'my-custom-menu',
'container_class' => 'custom-menu-class' ) );
?>

Most probably, you’ll want to place this code in the header.php file. This will place the menu at the very top of your site.

7. Customize Your Excerpts

Excerpts are short sample descriptions of your posts that you can display on your homepage or blog feed. By default, all excerpts have the same length and link text, but you can change that.

First, let’s alter the text of the link that takes you from the excerpt to the full post. This is usually “Read more” or “Continue reading,” but you can make it whatever you want by pasting the following snippet into your functions file:

function new_excerpt_more($more) {
global $post;
return '<a class="moretag" href="'. get_permalink($post->ID) . '"> Read the full article...</a>';
}
add_filter('excerpt_more', 'new_excerpt_more');

Here, the link text has been set to Read the full article…

customize WordPress excerpts by editing the functions.php file

Then, let’s change the length of the excerpt. Paste this code into your functions file:

function new_excerpt_length($length) {
return 20;
}
add_filter('excerpt_length', 'new_excerpt_length');

By default, the standard length is 55 words. However, in this example, it’s been set to 20. You can change the number to whatever you wish.

8. Generate a Random Background to Your Site

Finally, let’s end with a fun design trick. This tweak lets you randomly generate a new background color for your site every time somebody visits it. Start by adding the following code to the functions file:

function wpb_bg() {
$rand = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
$color ='#'.$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].
$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)];
echo $color;
}

This code generates the HTML tag for the colors, so all you need to do now is to make sure it gets applied to the page. To do that, you’ll need to find the <body> tag, which should look like this:

<body <?php body_class(); ?>>

This is usually in the header.php file but can be elsewhere, depending on your theme. When you’ve located the right line, simply replace it with the following code:

<body <?php body_class(); ?> style="background-color:<?php wpb_bg();?>">>

Save your file and open your website. You should see that it has a new background color:

create random background colors on reload by editing your WordPress functions.php file

Reload the page, and you’ll see a new color every time:

create random background colors on reload by editing your WordPress functions.php file

This is obviously not the right design choice for every site, but it’s a neat trick for some!

Edit Your functions.php File

The WordPress functions.php file is the perfect place to tinker with your site’s default functionality. It’s a powerful file that gives you a lot of control over your site once you understand how it works.

Depending on your WordPress theme, you might be able to use the built-in Theme File Editor to access and edit your functions.php file. Otherwise, you can access it via FTP. Then, you can use custom code to do everything from displaying the estimated reading time of a post to customizing your excerpts.

Do More with DreamPress

DreamPress Plus and Pro users get access to Jetpack Professional (and 200+ premium themes) at no added cost!

Managed WordPress Hosting - DreamPress

The post Everything You Need to Know About the WordPress functions.php File appeared first on Website Guides, Tips & Knowledge.



source https://www.dreamhost.com/blog/guide-to-wp-functions/

Creating and Mastering GA4 Explorations

In the switch from Universal Analytics (UA) to Google Analytics 4 (GA4) — which will go fully into effect July 2023 — a lot of things have...