WordPress Development https://wpmudev.com/blog The WPMU DEV Blog provides tutorials, tips, resources and reviews to help out any WordPress user Fri, 17 Mar 2023 06:18:27 +0000 en-US hourly 1 https://wordpress.org/?v=6.7.1 How This Web Dev Went from 0 to 60 (Websites) https://wpmudev.com/blog/how-this-web-dev-went-from-0-to-60-websites/ https://wpmudev.com/blog/how-this-web-dev-went-from-0-to-60-websites/#comments Fri, 17 Mar 2023 06:19:05 +0000 https://wpmudev.com/blog/?p=215067 This is the first in a series, Member Success Stories, where we ask WPMU DEV-ers who are killing it in the WordPress web dev business to share key contributors of their success with us – and you.

Today we welcome Phil, the owner of Capital Web Design, a Canadian web services agency based in Ottawa.

WPMU DEV: Congrats on your professional success, Phil. Please tell us straight away, how did you grow your business so fast?

Phil: I wouldn’t say the business itself grew that fast. I’ve been building websites in some way or another since the early 2000s. Either static sites coded by hand (HTML + CSS + Javascript), using frameworks (VueJS), or with WordPress.

I started my freelance web design company in 2014, after being approached to do a replacement build for what was a costly, difficult to maintain website – and that became my first client. From there I found small and medium businesses in my hometown that had old, unsupported and unmaintained websites, or who had no website at all.

As I continued my efforts, my business ethos emerged: help companies, nonprofits and individuals in my city build a web presence they can be proud of. I focused on creating bespoke WordPress web design based on well-supported multipurpose themes, WPMU DEV and other dependable plugins, and fully managed white-glove web hosting.

Since then, I’ve had the pleasure of working with 20+ clients, and have built 60 websites targeting a multitude of industries and commercial sectors.

WPMU DEV: That’s awesome. Did you know about WPMU DEV at that time?

Phil: I had known about WPMU DEV since around 2016-18, back when you offered dozens of plugins for all sorts of functionality. I couldn’t justify the cost of a membership then, but I popped in every so often to check and see what progress was being made.

In 2019, Hosting was added as a WPMU DEV service – and this really caught my attention. During the Black Friday promotion that November (lifetime reduced membership cost!), I joined as a member, and I can’t see myself ever leaving.

It was a perfect storm: high-quality plugins + managed hosting + 24/7 support + highly reduced cost.

WPMU DEV: So as you were building your clientele, you were putting together your professional tool box. Can you give us a peek inside?

Phil: The tools and services from WPMU DEV have been invaluable to me.

Plugins have provided me with consistency and reliability for all of the most important aspects of WordPress websites.

Knowing that I can count on Hummingbird and Smush for performance optimization allowed me to stop using other freemium plugins such as W3 Total Cache, Autoptimize, WP Super Cache and EWWW Image Optimization. I found these plugins were all good at some things, but had a lot of paywalled features that Hummingbird and Smush offered out of the box, for free.

Defender has been a great peace-of-mind addition to my repertoire, as the one-click recommended fixes are super straightforward and quite effective.

Forminator forms may be difficult at times to style with CSS, but that’s more than made up for in functionality. The drag-and-drop UI makes it much easier to build forms compared to Contact Form 7, and the amount of extras that are baked in (calculation, email routing, etc) blow other (often paid) form builders out of the water.

WPMU DEV: Aside from plugins, you mentioned our services have made a huge impact as well. Can you expand on that?

Phil: When it comes to services, it’s hard to put into words just how much The Hub and the associated Hosting have helped me throughout the last few years.

I have worked with hosting providers like 1and1, DreamHost, Media Temple, Digital Ocean VPS, and Bluehost. Each had their advantages, but in the end it always became a chore to use their services. It was clear that the quality of their offerings reflected the low cost they positioned themselves at. They were in a perpetual fight to undercut their competitors on price, at the cost of quality of service and support.

WPMU DEV Hosting came in late in the game, but out of the gate addressed two of the major concerns I experienced at other hosts: lack of support, and lack of trust in the infrastructure.

By having dedicated resources (versus shared), the web servers were consistently fast, reliable, and offered premium features such as staging, backups and WAF.

WPMU DEV: Walk us through a typical work day; what you reach for the most, and your usual workflow.

Phil: I keep The Hub open in a tab at all times, refreshing it every once in a while to keep track of ongoing community discussions, website maintenance statuses, and plugin updates.

I subscribe to key email notifications to receive alerts of technical issues on my managed sites, as well as member discussions in the WPMU DEV member forums, blogs and newsletter.

When a technical issue occurs, I’m able to troubleshoot it quickly. If I’m unable to resolve it on my own, the LiveChat support is always there to help me right away.

WPMU DEV has allowed me to optimize my workflows across the board, in areas like:

  • Faster site creation with one-click managed WordPress server provisioning from The Hub.
  • Easier client invoicing using Client Billing.
  • More efficient website monitoring and maintenance through The Hub.
  • Lower maintenance effort required with WPMU DEV plugins.
  • Faster technical troubleshooting with the LiveChat support.

WPMU DEV: Outside of your own talent and determination, what would you say has contributed most significantly to your growth?

Phil: WPMU DEV has reduced my server build-out time from 30 minutes to 3 minutes (90% reduction). Over the past few years I’ve stood up well over 75 servers, so this has saved me many hours of effort.

At the time of joining, The Hub allowed me to manage about a dozen sites from a central location as opposed to manually logging in to each separate site. This was a reduction of biweekly maintenance effort from approximately 60 minutes to 2 minutes.

Client billing and streamlined invoice creation allowed me to save approximately 20-30 minutes per invoice creation, which throughout the past few years I estimate has saved me over 30 hours of work.

All of these time and effort savings have allowed me to comfortably take on more projects and clients.

Since joining WPMU DEV, my completed projects count has grown approximately 416% – with each project being more efficient to produce than the last.

WPMU DEV: As a self-proclaimed diehard fan, you know we’re constantly upping our game and adding new features and services to our offerings. What’s a newer release that you’re really getting into?

Phil: Reseller focus. I look forward to adding WPMU DEV automated site provisioning via the reseller offerings, as well as domains and email reselling.

WPMU DEV: One last question; let’s close it out with a fun one. If you could talk to yourself at the start of your career, what would you say?

Phil: At the start of my career, I often looked up to senior staff who seemed wise beyond their years. I was afraid of making mistakes or breaking something, for fear that those-who-never-broke-anything would look down on me.

I would try to explain to a younger me that wisdom comes with experience, and experience comes from doing things, failing, and working through the failure.

The more things you work on, the more you get exposed to what works and what doesn’t. Failing or breaking something isn’t strictly negative, because every failure is a learning opportunity: troubleshoot what went wrong, understand how to fix it, and implement a solution.

Do this cycle enough times and you start to pre-emptively detect patterns, plan for success, and you get faster at fixing problems. Don’t be afraid of failure because the more you fail, the more you learn and the wiser you will become.

That wraps up this premiere episode of our Member Success Stories. Thanks to Phil for his candid, insightful answers in our interview.

Phil is one of WPMU DEV’s Agency Partners, and usesCapital Web Design - Ottawa Web Design his 20 years of web design experience to achieve one goal: give back to his hometown by building modern websites for businesses and nonprofits in the Canadian capital.

You can reach Phil via his agency partner listing or visit Capital Web Design.

]]>
https://wpmudev.com/blog/how-this-web-dev-went-from-0-to-60-websites/feed/ 19 2023-03-17T06:19:05Z
5 Brilliant Companion Products to Make Your WordPress Websites Compliant https://wpmudev.com/blog/companion-products-for-compliant-websites/ https://wpmudev.com/blog/companion-products-for-compliant-websites/#comments Thu, 09 Mar 2023 14:39:58 +0000 https://wpmudev.com/blog/?p=214898 Compliance on websites isn’t a fringe component. It’s a serious, legal matter, which can seriously affect your business.

Legal fees can be expensive, and add up quickly. Also, law is complicated, and can vary based on where you live and do business from. How does one accomplish compliance without getting their own law degree? (Or having a best friend who passed the bar exam?)

There is a way you can dot your I’s and cross your T’s, get all your ducks in a row, check all the boxes, cover your bases (this IS a post about full compliance, so one expression didn’t seem like enough 😀) – without draining your bank account, or losing your sanity.

Because WordPress is far and above the leading CMS, there are a good number of options when it comes to compliance regulation companion products.

We looked into the pool of offerings, picked the ones we thought were smart, solid, and sound, and are presenting them to you here.

Keep reading, or jump ahead to any section:

First up, let’s examine…

Why Compliance is of Utmost Importance

Privacy is a major factor in today’s world, and personal information is protected by a fast-growing assortment of legal rights.

Throughout the first three-quarters of the 20th century, collected data was relatively minimal, there were few ways to store it, and demand for its collective use wasn’t really a thing.

However, from the ’70s through today, as the inherent value of data grew – along with improved methods to collect, store, use, and profit from it – so has the need for legislation to protect it.

Living in the era of Big Data, where the sheer volume of data has increased to previously unimaginable amounts, a true premium has been put on an individual’s rights to protect it.

Non-compliance with the legal safeguards comes with steep fines and other serious penalties.

A Timeline of Enacted Privacy Protections

While data protections may have started slowly, they will continue to pick up speed as the by-product of ethical examination and pivotal litigations surrounding privacy.

Let’s take a peek at the landmark protections in the history of privacy legislation.

The Privacy Act of 1974 established the Code of Fair Information Practice on the collection, maintenance, use, and dissemination of personally identifiable information from US federal agencies.

The Data Protection Directive was adopted by The European Union in 1995. The principles set forth were aimed at the protection of fundamental rights and freedoms in the processing of personal data. This was superseded by the GDPR in 2018.

The Health Insurance Portability and Accountability Act (HIPAA) was established in 1996 to protect Personally Identifiable Information maintained by the healthcare and health insurance industries from theft and fraud, safeguarding people’s medical information from being used without their consent.

The Children’s Online Privacy Protection Act (COPPA) was enacted by Congress in 1998 and requires the Federal Trade Commission to issue and enforce regulations concerning children’s online privacy. The amended Rule became effective on July 1, 2013.

The General Data Protection Regulation (GDPR) for data protection and privacy became law in 2018 in the European Union (EU).

The GDPR applies to the transfer of personal data outside of the EU and EEA (the European Economic Area is the countries of Iceland, Norway, and Liechtenstein), and replaced the Data Protection Directive from 1995.

Shortly thereafter, State Privacy Legislations in the US started…

  • California Consumer Privacy Act (CCPA) – signed into law 2018; effective 2020
  • California Privacy Rights Act (CPRA) – also known as CCPA 2.0, enacted in 2020
  • Virginia Consumer Data Protection Act (VCDPA) – legislated in 2021; effective January 1, 2023
  • Colorado’s Privacy Act – will be effective July 1, 2023
  • Connecticut’s Personal Data Privacy and Online Monitoring Act – will be effective July 1, 2023
  • Utah’s Consumer Privacy Act – will be effective December 31, 2023

While the US does not have a single, comprehensive, internet privacy law, one is currently being proposed by federal privacy legislation: the American Data Privacy and Protection Act (ADPPA). If passed into law, it will supersede all state privacy laws. Until then, it’s up to individual states to pass legislation that protects customer data.

Which Components Do You Need?

At this point you may be wondering, with so many already existing and soon-to-be-effective legal stipulations on data, which ones are you required to adhere to as a website or app owner?

That’s what we’ll lay out now in…

Compliance Requirements

To best meet overall compliance, websites should minimally have:

  • Privacy Policy
  • Cookie Policy

… and …

  • Consent (Record of Consent)

Let’s put a pin in Consent for a bit, and come back to it after we look at the policies.

A Privacy Policy addresses all the different ways your website or app might collect, process, and store data from users, both online and off.

A Cookie Policy specifically addresses how you use cookies and third-party services.

Because of the overlap, websites sometimes include a cookie policy in their privacy policy, as part of the overall data collection.

However, cookie policies need to be regularly updated (as cookies are dynamic and often change upon successive visits), whereas policy policies tend to be static.

More importantly, if you fall under the scope of the GDPR, your Cookie Policy must be separate from your Privacy Policy.

You can still incorporate a short Cookie Clause in your Privacy Policy, or cross-reference the agreements (for example, link your Cookie Policy to your Privacy Policy), but you shouldn’t combine the agreements into one.

Even if you don’t fall under the scope of GDPR, it’s safer and smarter to create a separate Privacy Policy and Cookie Policy, instead of merging them into one.

Let’s dive a little deeper into both of these important policies.

Privacy Policies

Most laws around the world require a privacy policy.

Privacy policies are legally required agreements when collecting any personal data from users (e.g. payment details, address and phone number, cookie data), regardless of the platform used (e.g. website, mobile app, desktop app, etc).

You may need a privacy policy to use third-party APIs and services (e.g. Instagram, Google Analytics, or Google Adsense), or to list your app in a commercial marketplace such as the Apple App or Google Play stores.

Without a privacy policy, you risk your business getting hit with hefty fines and/or having your website taken down, especially if you’re found to be in breach of privacy laws.

Key privacy policies or agencies, by country of origin are:

  1. Europe/European Union – GDPR (businesses in or operating with EU/EEA)
  2. United States – by state (CCPA, CPRA, CalOPPA, VCDPA)
  3. Canada – PIPEDA
  4. Australia – The Privacy Act 1988
  5. Germany – BDSG, and DSGVO (German name for the GDPR)
  6. France – CNIL (the commission overseeing privacy policies)
  7. South Africa – The POPI Act (POPIA)
  8. Brazil – LGPD (broadly aligns with the GDPR)

Lesser-known privacy laws exist around the world as well; the above is not to be considered an exhaustive list.

While privacy policies are generally referred to by location of origin, they can extend to any region that does business with them. Meaning, don’t assume that if you reside outside of Europe that the GDPR doesn’t apply to you.

The EU’s GDPR and US state laws (#1 and #2) are the most broadly reaching and widely followed privacy policies. But that’s not to say that the others don’t matter; it’s important to research any that might apply to your business.

Cookie Policies

Cookie policies are legally binding documents that inform website or app users how a company engages in data tracking and online privacy.

Cookie identifiers are considered to be personal data by the GDPR, so its rules apply to cookie usage as well. Also, any personal data collected by cookies falls under the GDPR’s jurisdiction.

The ePrivacy Directive (ePD) of the EU – nicknamed the “Cookie Law” – requires security measures be put in place to protect personal data. This regulates cookie usage, email marketing, data minimization, and other aspects of data privacy, and is largely responsible for the cookie consent forms that you encounter on most websites today. (Sidebar: This doesn’t replace the Cookie Law I grew up with; “Don’t ever serve chocolate chippers without milk.”)

The ePrivacy Regulation (ePR), the details of which are currently being hammered out by legislators, will replace the ePD once it’s passed into law.

Consent / Record of Consent

Taking out that pin that we placed earlier, it’s time to look at Consent.

The important distinction between Policy and Consent is this: Policy discloses details regarding the use of cookies, while Consent informs and records the allowances from users regarding usage.

Make sure you incorporate consent into your Privacy/Cookie policies. Full GDPR compliance means storing proof of Consent, and being able to demonstrate or retrieve details should they be requested.

I can’t stress this enough: having Privacy/Cookie policies without consent could cause major problems for you.

Additional Legal Protections

While protecting user data is of paramount importance, privacy isn’t the only concern for someone managing websites.

There are other important, legal considerations when it comes to engaging the public online.

We’ll take a look at them now.

Terms & Conditions

Unlike Privacy Policies, there are no laws that require you to have a Terms & Conditions agreement, though it is highly suggested to have one.

Without a T&C, it’s much more difficult to enforce your rules and community guidelines, copyright protection, or other issues that could arise from the misuse of your website/app content.

The majority of the public will act courteously, but that’s not who you’re protecting yourself from. It’s the small percentage of outliers who can sometimes do the most damage. Having explicitly stated Terms & Conditions can offer basic protections for you and your business, limiting your liability and declaring your rights over the content you create, in case anyone engages in abuse, intellectual property theft, or unlawful behavior.

The most common reasons for Terms & Conditions are to:

  1. Prevent abuses
  2. Protect your creative content
  3. Terminate accounts
  4. Limit your legal liability
  5. Set your governing law

If you’ve ever seen a clause in a T&C stating where (geographic region) any dispute resolution must take place, that falls under governing law, and is quite useful if you don’t want to litigate legal matters in a country outside of your own.

Disclaimers

Disclaimers can be used to offset liability from a business to a client in ambiguous or gray legal areas, or where they are required by law.

Without them, you are opening yourself up to legal liability or the possible endangerment of others, especially on sites that share advice, DIYs, or promote/sell products (most of which come with claims).

Websites and eCommerce stores benefit from disclaimers in that they:

  • Let users/customers know that the content is not legally binding advice, nor should it be solely relied on
  • Limit the liability of the website/store in the event someone has an unsatisfactory result from its advice or products

Some of the most common disclaimer types are:

  • Copyright
  • Fair Use
  • No Responsibility
  • Views Expressed
  • Offensive Content
  • Past Performance
  • Errors and Omissions
  • Affiliates / Affiliate Links

While we’re on the subject, here’s an example in actual use:

Disclaimer: WPMU DEV is not a legal entity, nor does it claim to be an authority on the laws of any region, country, or the internet. While this post contains well-researched content from respected sources, it is for informational purposes only and not intended as a substitute for professional legal advice. As such, we cannot be held liable for any omissions or errors contained within.

That said, let’s get to the tools and services of the compliance trade, with…

Our Top 5 Picks for Compliance Companions

Some of these are actual WordPress plugins, while others are content generated directly in the company’s website.

Regardless of how you access them, all offer plenty of bang for the buck, and value for the venue (I’m coining this phrase to mean free products and their providers 😉).

GDPR Cookie Consent and Cookie Yes (by WebToffee)

WebToffee has a sisterhood of plugins, with versions available on two separate websites: CookieYes and WebToffee, plus the free version on the WordPress repository.

CookieYes is one of the most used WordPress GDPR cookie compliance plugins, with 1 million+ active installations and 5 out of 5 stars.

Starting with the free WP.org plugin version, you get a goodly amount of features, including:

  • a cookie consent banner with Accept/Reject options
  • single click automatic scanning and categorization of cookies
  • display list of cookies on your cookie policy page by using a shortcode
  • adds a cookie banner to your WordPress website to show compliance with GDPR
  • fully customize the cookie notice so it blends with your existing website (change colors, fonts, styles, position on page; even how it behaves when you click “Accept All”)
  • has a Cookie List module so you can easily show what cookies your site uses and display them neatly in a table on your Privacy & Cookies Policy page
  • can be configured to have a CCPA/CPRA ‘Do Not Sell or Share My Personal Information’ control to the cookie notice

The free version also includes a connection (also free) with the CookieYes web app to access advanced features (cookie scan, consent log, etc) and manage all settings from the web app account. Note: You can still use most of the features from within the WP dashboard, without connecting to the web app.

cookie yes dashboard
The CookieYes dashboard gives you a nice snapshot of information.

One of the advantages here is the dashboard, which includes a Consent section. You can view or access details on user consent should you ever be audited and need to show this information. It even allows you to download this consent data in CSV format.

From the WP plugin dashboard, there’s a lot you can do:

  • Check banner status (active, inactive), regulation type (GDPR), last cookie scan, language
  • Customize banner
  • Maintain cookie list, add new cookies
  • Change/edit default banner language
  • Generate a Privacy or Cookie policy for your site

Add the user guide provided for setup, along with a video walkthrough, and you can see why this plugin is so well loved.

cookie yes customize consent prefs
CookieYes banner and consent customizations.

If you want to go for a CookieYes paid plan, you have three tier options, payable per domain, monthly or annually. Each tier adds more pages per scan (600, 4K, 8K) and pageviews (100K, 300K, unlimited), plus a couple of additional features – like custom branding, and geo-targeted cookie banners.

As a third option here, we have the paid, premium version of GDPR Cookie Consent Plugin (CCPA Ready) – available from WebToffee’s website.

The final offering in the WebToffee family of compliance options, GDPR Cookie Consent remains in the territory of fastest-growing WP consent plugins, verifiable by a mass of happy users.

webtoffee GDPR Cookie Consent display options
GDPR Cookie Consent offers a variety of notices, all with customization.

As far as features, most are available and common to both the GDPR Cookie Consent and the CookieYes paid plans. However, the GDPR Cookie Consent plans do not have:

  • Auto-translation
  • Global privacy control
  • Do not track
  • Monthly scheduled scan
  • Privacy policy generator

GDPR Cookie Consent pricing has three tiers, based on the number of sites (1, 5, 25) you want to use it on. Each includes one year of updates and support, and a 30-day, money-back guarantee.

The primary difference between The GDPR Cookie Consent and CookieYes paid plans is the technology they rely on. The CookieYes web app is a SaaS that requires huge cloud computing, storage, and security facilities. (This is also why the CookieYes paid plans are based on scans and pageviews.)

Bonus points for their support: I reached out as a free user to clarify a few points in this section and got a detailed response in less than half a day. (High five to Mark!)

iubenda

Iubenda has been quickly rising in the ranks of compliance with their all-in-one solution, currently sitting at 100K+ active installs and a 5/5 star rating on WP.

If you’re looking for that extra layer of comfort, iubenda has it, with attorney-level compliance solutions, all of which are fully WCAG Level AAA Compliant.

The free version of iubenda compliance solutions support the GDPR, LGPD, and US State Laws (CCPA/CPRA and VCDPA).

Content is auto-updated when laws change, so it’s always up-to-date. (Their built-in site scanner runs periodic scans on your site and alerts you if it detects something that should be added to your compliance documents.)

The free version comes with the following features:

  • Privacy and Cookie Policy Generator
    • a single policy, on one site, in one language
    • up to 4 (non-Pro) service clauses
    • does not include Cookie Policy
  • Privacy Controls and Cookie Solution
    • up to 25K page views/month (for compliance with GDPR, LGPD & ePrivacy and US state laws)
iubenda privacy controls and cookie solution settings
iubenda privacy controls and cookie solution settings.

You can get the free version of iubenda from the WordPress plugin repository.

The majority of iubenda’s standout features are found in their paid/pro versions, trusted by over 90,000 clients in more than 100 countries. These allow for multiple policies, sites, and languages, as well as Privacy Control & Cookie Solutions, a Terms & Conditions generator, a Consent Database, and more.

Privacy Control & Cookie Solutions helps you meet complex legal requirements at the click of a button, as well as create a fully customizable cookie banner.

Terms & Conditions offers powerful features like plug-and-go integrations for popular platforms and legislation monitoring. It’s customizable from hundreds of combinations, available in 10 languages, and capable of handling even the most complex, individual scenarios. Optimized for eCommerce, marketplace, SaaS, apps and more.

The Consent Database activates with one click to track, store, and manage consent and privacy preferences for each of your users all in one place, allowing you to easily upload proofs of consent and legal notices in PDF format.

They also offer an Internal Privacy Management, which documents all the data processing activity within your organization. To comply with privacy laws (particularly the GDPR), companies must record how they store and use the data they collect from their users.

Additional features in the paid plans are:

  • More Compliance Laws, like DSGVO, RGPD, UK-GDPR, CalOPPA, PECR
  • Cookie consent analytics provided for high-traffic sites
  • Detects bots/spiders and serves them a clean page so that your SEO efforts are never compromised
  • Built-in compatibility with WordPress comment form, Contact Form 7, and WP Forms; can also be manually integrated with any type of web-form

Pricing is offered as bundles with 3 tiers, based on number of license slots, with paid add-ons – Terms & Conditions, and Consent Database – available as extras.

Or, you can go with their Custom plans, with 3 tiers, broken out by options for Privacy & Cookie Policy, Privacy Controls & Cookie Solution, and Terms & Conditions.

iubenda pricing models
iubenda’s pricing models with inclusions listed.

Head over to iubenda’s website for a more in-depth read about their compliance offerings, or to purchase one of their plans.

TermsFeed

TermsFeed doesn’t have a plugin; everything is generated directly from their website. But in no way does that detract from their fantastic functions.

The TermsFeed website has an abundance of compliance offerings, most of which they charge nothing for.

Since 2012, TermsFeed’s all-in-one compliance software has helped businesses get (and stay) compliant with the law, and the multitude of glowing, five-star reviews corroborates that.

Popular free features include:

  • Privacy Policy Generator
  • Terms & Conditions Generator
  • Privacy Consent
  • Cookie Consent
  • EULA Generator – gives users the right to use a copy of your product after they acquire it, through a granted license (with or without limitations)
  • Disclaimer Generator
  • Return and Refund Policy Generator
  • Shipping Policy Template – no generator for this, but a detailed, helpful template to assist businesses in creating

They also offer these additional, not-as-common free tools:

  • CCPA Opt-out – Free tool to manage opt-outs for CCPA
  • I Agree Checkbox – Free tool to enforce your legal agreements and policies on web forms
  • Embed Consent – Free tool to block embeds (YouTube, Twitter, Google Maps) from loading until you’ve got user consent
termsfeed compliance toolbox infographic
The TermsFeed site has a ton of helpful, visually appealing infographics.

All of the generators operate in the same, simple three-step: 1) Create a free account. 2) Choose what you need. 3) Download and integrate.

You answer a few quick questions, and your custom policy is ready in minutes, available to download in multiple file formats – which you can link to, edit, or update.

Or, download their handy privacy policy template (available in a variety of formats: HTML, DOCX, Google Docs), and write your own.

And the output isn’t limited to just websites; you can use it to create for mobile apps, eCommerce stores, third-party tools, SaaS, and even a Facebook page.

The TermsFeed website is well organized and chock full of helpful information, making an easy task out of finding what you need.

The majority of compliance agreements and policies on the TermsFeed website are essentially free. However, they do offer some optional, premium agreements with additional clauses to protect your business interests.

Paid items are available in two ways:

  • Privacy Consent Solution, which gives you access to all features, payable month-to-month, or yearly (with a discount).
  • Per Policy/Agreement, which allows you to select any number of policies from their huge compliance toolbox, and pay a one-time fee, per item

Both payment structures come with a 7-day refund policy, and 100% money-back guarantee.

termsfeed privacy policy blog articles summary
A summary recap of Privacy Policy blog articles in TermsFeed.

As far as videos, walk-through processes, and documentation go, out of all the sites I reviewed in this article, they had the most. On YouTube alone, I counted close to 200 explainer videos (on their content specifically, and policy terminology in general), plus dozens of tutorials for using on a myriad of website types (Wix, Weebly, Squarespace, Webflow, Shopify, etc) in addition to WordPress.

My final thoughts: the TermsFeed website is an embarrassment of riches, with compliance offerings galore, and little to no limitations on their use. Even the premium, paid-for options won’t break the bank.

Visit the TermsFeed website for tools, tips, and custom provisions, or their YouTube channel for a ton of valuable, well-produced info.

Complianz

Complianz is another widely used compliance plugin, available for free on the WP repository: Cookie Consent – aka the Privacy Suite for WP. (They offer an additional one for Terms & Conditions as well.)

Active installations are at 600K (and climbing), and rated 5/5 stars.

Complianz is a GDPR/CCPA Cookie Consent plugin that supports GDPR, ePrivacy, and more, with a conditional Cookie Notice and customized Cookie Policy, based on the results of their built-in Cookie Scan.

Free features include:

  • Cookie Notice configuration for your specific region (EU, UK, US, Australia, South Africa, Brazil, and Canada; or use one Cookie Notice worldwide)
  • Cookie Consent and Conditional Cookie Notice with custom CSS and customizable templates
  • Automatic configuration of your website based on wizard questions, WordPress scans, and dedicated service and plugin integrations
  • Proof of Consent for user registration (respects GDPR data minimization guideline)
  • Automatically detects if you need a Cookie Notice (aka Cookie Banner or popup)
  • Cookie policy generation through an easy wizard
  • Offers “Do Not Sell My Personal Information” (for CCPA/CPRA)

Complianz is one of the few WordPress native solutions, integrated with a wide variety of plugins and services. Once configured through the wizard, Complianz will work with most of your plugins and embedded content – right out of the box. Including our very own Forminator, Beehive, and the WPMU DEV Dashboard plugin (where you can integrate Complianz to allow site visitors to reject dashboard analytics statistics cookies).

Like iubenda, their policies are drafted by an IT Law Firm, and are WCAG Level AA and ADA Compliant. They closely follow the latest developments in ePrivacy regulation, the proposed Cookie Law for the EU, and other legislation worldwide, so you can be sure the content is spot-on, legally speaking.

Complianz also has premium, paid offerings for compliance, available from their own website.

Their website has documentation, and as a premium user, you get dedicated support from privacy professionals and developers who (and I quote) “don’t quit until a solution is reached”.

complianz offerings screenshot
Complianz offers a full privacy suite for WordPress.
complianz premium vs free features chart
Legal docs and Consent Management offerings on Complianz, free vs paid.

Easily install the free Complianz Privacy Suite plugin from your WordPress dashboard. For the premium version, you’ll need to download from your account on Complianz.io, or use the link in your purchase confirmation, along with your license key.

In addition to the free version, paid plans are offered as 3 tiers, priced per number of sites (25, 5, 1). All include the full shebang of required legal documents, compliant in multiple regions, along with records of consent, data request processing, A/B testing and statistics, and detailed cookie descriptions.

Termly

While Termly does have a plugin on the WP.org repository, it’s outdated, and I don’t recommend using it. But that doesn’t make their compliance options any less capable or appealing.

Instead of the WP repo, head over to Termly’s website, where everything you need is easily accessible and kept fully up to date.

Termly compliance offerings
Compliance solution offerings from Termly.

The Termly website comes with a host of features, ranging from a single policy to a full suite of compliance solutions.

Here’s a breakdown of Termly’s top features:

  • Consent Management Platform
    • Manage consent on your website or app while providing a robust and flexible solution to compliment your business needs and regulatory requirements
  • Policy Generators
    • Choose from the ever-expanding list of legally vetted policies to protect your business and meet your compliance needs
  • Additional Legal Protection Generators
    • Easily create other Agreements and Notices to further protect your website (like: Terms & Conditions, Disclaimers, EULAs, Shipping Policies, Refund and Return Generators)
Termly's all-in-one cookie consent solution
Termly’s all-in-one cookie consent solution.

Termly’s free plan provides you with one legal policy, four edits, and 10K/month banner visitors, as well as their basic compliance tools, which are:

  • Privacy Regulation Monitoring
  • Cookie Policy & Banner
  • Cookie Script Auto Blocker
  • HTML Embeddable Policies
  • Quarterly cookie scans

In addition to their free/basic plan, Termly offers 3 paid tiers, priced per website. The first two go by number of policies, policy edits, and banner visits, and are payable per month or annually. The third tier is a custom “contact us” option.

With 4.5 out of 5 star rating on Trustpilot, Termly is trusted and revered by thousands.

Better Compliance and Reliance with WPMU DEV

As you can see, responsible data management is not only good business practice, it’s also the law.

In today’s landscape where massive amounts of data, along with infinitely more ways to store and use it are the norm, diligence is required in its care and handling, especially if you operate an online business (your own, or as an Agency for clients).

Regardless of what kind of business it is, where it is located, or where your visitors reside, you are bound by certain legalities.

Ignorance is not a defense, so compliance can be the difference between being successfully safe or professionally sunk.

Beyond research and recommendations for meeting compliance requirements, WPMU DEV works hard to keep your websites and web development business operating at peak efficiency.

That includes our free products and services, and our premium membership offerings – a suite of pro plugins (protection, optimization, form creation, SEO, and more), five-star always-on support, and sleek all-in-one site management tool. Plus our fast, dedicated, best-value-in-the-biz Hosting.

If you’re not a member yet, you can start your 7-day, no obligation free trial today, and instantly catch up on what you’ve been missing.

]]>
https://wpmudev.com/blog/companion-products-for-compliant-websites/feed/ 9 2023-03-09T14:39:58Z
6 Key Web Developer Trends to Watch in 2023 https://wpmudev.com/blog/web-developer-trends/ https://wpmudev.com/blog/web-developer-trends/#comments Thu, 16 Feb 2023 22:04:50 +0000 https://wpmudev.com/blog/?p=214651 If you’re in the field of web development, you might want to pay attention to these industry-predicted trends.

There are a lot of design and development trends floating around the internet. Researching this topic, I came across articles that listed upwards of 50. While many of these are legitimate topics of interest, most of them weren’t headline worthy.

So how did I land on a top 6? First and foremost, the topic had to be relevant and prevalent (after all, that is the definition of trendy). In addition, they had to strike me as important and valuable when it comes to web development specifically.

If these aren’t already on your radar, chances are they will be soon. Getting a good grasp on these noteworthy topics can really help you elevate your web development business.

Here’s a quick overview of what we’ll cover:

Since AI is a common denominator in all of the burgeoning tech we’ll look at in this article, it seemed a brief history on the topic would be in order.

A Primer on AI

The very first notions of AI came in the form of myths and rumors; artificial beings endowed with intelligence or consciousness by some master craftsmen. You know, your typical origins story.

Philosophers and thought leaders in other disciplines continued to discuss the essence of what would become AI, and in the 1940s the first programmable digital computer was created. However, with the ability only to execute commands (not store them), it lacked the prerequisite for intelligence: formal reasoning.

The ’50s saw mathematician Alan Turing’s Theory of Computation, suggesting it might be possible to construct an electronic brain. He postulated that machines could use information to solve problems and make decisions, much like humans, and in 1956, the field of artificial intelligence research was founded as an academic discipline.

Through the ’60s and ’70s, AI thrived, with computers able to store more information while simultaneously becoming faster, cheaper, and more accessible.

AI continued to pick up speed in the ’80s and ’90s. Learning techniques and expert systems were introduced and popularized, while governments and industries poured billions of dollars into revolutionizing AI. Alas, the loftiest goals didn’t come to fruition, and investors withdrew funding.

During the ’90s and 2000s, many of AI’s landmark achievements were met, despite government funding and public interest taking a backseat. In 1997, IBM’s chess playing computer program, Deep Blue, defeated the reigning world chess champion grandmaster. Later that same year, Windows implemented speech recognition software.

Since the turn of the century, AI has continued to prosper. By 2016, AI-related hardware and software surpassed the $8 billion mark, and the New York Times deemed the interest in AI “a frenzy”.

In today’s era of “Big Data” (characterized by volume, velocity, variety, value, and veracity), AI continues to propel forward, at times its capabilities not only reaching but surpassing computational power. (See Moore’s Law.)

With AI at the forefront of almost any tech you can think of, the possibilities seem endless, and the opportunities exciting.

So, without further ado…

The Top 6 Trends in Web Development

Let’s get straight to the heart of the matter. Here are the top 6 trends in web development for 2023, starting with…

AI Chatbots

AI Chatbots, or AI Assistants, are extremely prevalent in today’s world, and expected to grow substantially. In fact, SEMRush predicts a 33.2% year-on-year growth rate from 2020 to 2027.

chatbot stats
Revealing AI Chatbot stats. Image Source.

AI chatbots help millions of people and businesses perform operations faster by using text or voice prompts. They also offer 24/7/365 availability, which is crucial to providing ready access to customers around the world in every time zone.

Considered to be one of the most influential technologies that will shape the future of web development, AI chatbots are smarter than regular chatbots. Due to use of natural language processing (NLP) and machine learning (ML) technologies, they better understand what the user wants, then tailor that experience to the individual.

AI chatbots can engage in complex conversations easily without the human intervention quotient. Because they analyze behavior and solve problems, their AI learning algorithms become smarter with every query they handle.

The impact of AI chatbots is substantial. Simply put: Chatbots enhance and streamline the customer experience. More specifically, they’ve been shown to lower customer complaints (i.e., improve satisfaction), improve lead capture and contact flow, and increase sales. And it goes with saying that the more customers enjoy an online experience, the more likely they are to purchase from the company providing it.

Web developers can benefit from AI-powered chatbots in a couple of ways, like replacing navigational elements on websites to make development easier, or integrating chatbots with messengers, so fewer applications need to be developed.

With customer engagement being a key indicator of business success, you really can’t afford to ignore the benefits of AI chatbots, especially as they become even more sophisticated in the near future.

Voice Assistant

We are currently in the midst of the voice search era. Every smartphone is equipped with digital voice assistants, while their home-bound counterparts (smart speakers) are skyrocketing in popularity.

The most common ways to interact with voice assistants is through smartphones, smart cars, and smart speakers – in that order. The four biggest providers of voice assistants are Apple’s Siri, the eponymous Google Assistant, Amazon’s Alexa, and Microsoft’s Cortana.

Though there are a vast number of reasons that people use voice assistants, top tasks include making calls (or sending texts), getting directions, playing music, and finding nearby businesses.

Recent data in The Global State of Digital 2022 reveals that 22.5% of users worldwide use voice assistants each week on the internet, spanning a vast range of ages (16-64 years).

percentage worldwide use voice assistants
Key voice assistant stats from The Global State of Digital report.

Additionally, the voice assistant application market size is projected to grow from 2.8 billion in 2021 to 11.2 billion USD by 2026, at a Compound Annual Growth Rate (CAGR) of 32.4%.

How did voice assistants become so popular? Partly due to ease of use; basic communication skills are already present in humans, so both kids and seniors can adapt to voice interfaces with a minimal learning curve. Secondly, digital voice assistants are commonplace on smartphones, so the tech is within easy reach at no additional cost.

Voice Assistant technology is also being implemented to make sites more accessible for those who are hearing and sight-impaired.

Because of their massive use, voice search results will start to rank higher and more prominently on search engine result pages. Which means companies will place emphasis on optimizing their products and services with voice search at the forefront.

This provides a good deal of opportunity for web developers when it comes to voice assistant technology and incorporating it into the development process.

A good place to start taking advantage of this trend is by optimizing structured data for voice search in WordPress.

Progressive Web Applications (PWAs)

Progressive Web Applications (aka PWAs) are web applications that run independently of a browser and interact with the customer as a native app. Some prime examples are Google Maps, Starbucks, and Spotify.

pwa dev preferable
Indications that PWA is preferrable. Image Source.

PWAs are currently among the top trends in web development, and expected to fully replace traditional web apps in the near future.

Using a single codebase, developers can code Progressive Web Apps to work with modern APIs, delivering enhanced capabilities and reliability that can reach anyone – regardless of their location or what device they’re on.

PWAs improve the overall user experience because of these key benefits:

  • fast
  • relatively low cost
  • quick to launch/distribute on the market
  • install quickly and automatically update
  • save on device power and storage
  • work well offline (or with bad connections)
  • boost website engagement/conversion
  • maintenance and updating is seamless
  • fully immersive experience

Another plus for PWAs is that Google prioritizes web apps that load quickly on mobile devices. Because they reduce page load time, PWAs dramatically improve search result rankings.

According to Statista, mobile sales in the global market are projected to reach $8.1 billion in 2026. That means people will likely choose their mobile devices over their non-mobile counterparts for most of their purchasing needs, leaning directly into what PWAs provide.

PWAs are responsive, secure, easy to install, scalable, and reliably connected, making them a perfect fit for many B2B and B2C uses.

Tip: Do you use the Avada theme on client sites? Then check out our article on how to speed up and optimize Avada using our Smush and Hummingbird plugins with Avada’s own PWA plugin.

Single-page Applications (SPA)

Single-page applications (or SPAs) are one of the most critical technology trends in web development today.

SPA architecture
Architecture of an SPA. Image source.

An SPA is a JavaScript-based web application. Instead of loading separate HTML pages from a server, it loads a single, specific page to visitors, dynamically updating its content without refreshing the page.

Social media sites (think Facebook and Twitter), as well as Gmail and Google Drive, are among the most well-known SPAs.

Since most devices support it, SPA technology is cross-platform in nature. They even perform well with a slow internet connection or when offline, loading cached content when users launch the site. SPAs are also better equipped to work without server-side codes infused with API technology.

All of this means that SPAs operate fast and keep users attention, leading to greater engagement and reduced bounce rates.

SPAs are easy to create, cost-effective, and consume less server space, making them practical for both end users and developers.

Tip: Feel like getting into SPA and reading some relaxing articles to get you in the mood? Then check out these bubbly tutorials:

Internet of Things (IoT)

Long foreshadowed as the wave of the future, the Internet of Things (or IoT) is a movement where objects are given network connectivity that didn’t historically have it, in order to send and receive data.

IoT is one of the most rapidly emerging technologies in web development, with Statista indicating the number of IoT-connected devices will reach more than 29 billion by 2030.

IoT connected devices chart
IoT-connected devices worldwide by year. Image source.

IoT objects can range from home devices, to appliances, and wearable technology, as well as cameras, sensors, and signaling equipment – all helping to meet user needs more quickly.

Furthermore, IoT can make many otherwise non-connected devices accessible from your phone.

A popular example would be the Google Nest package of products, which provides users with features like media, alarms, lights, and more, simply by using their voice.

IoT-connected devices have constant data transfers, allowing companies to engage users with their services at incredible speeds, while creating a personalized experience.

IoT is scalable, as it distributes and collects data but isn’t dependent on the volume of data. It is also reliable, providing accurate results in an expedited fashion. Additionally, it employs powerful security tech to protect business and user data.

IoT’s smart ecosystem provides a wide range of benefits that can be incorporated into websites and mobile apps, analyzing customer behavior to improve the user experience while providing developers with insights.

Motion UI

Motion UI, under the umbrella of motion design, is expected to be a major web design trend in the coming year. The principle is minimalistic design coupled with sophisticated interactions that look amazing and draw the user’s attention.

Motion UI in its glory. Source: Taras Migulko for emote_agency on Dribbble.

Motion UI is a powerful front-end technology that can create customizable, animated UI elements and CSS transitions using SASS libraries.

Popular motions include background animations, animated charts, and modular scrolling, and transition actions like sliding, spinning, bouncing, etc. All of these can cater to individual styles, and aim to catch and keep users’ attention.

Motion UI is generally compatible with all web technologies, and allows flexibility in placement on websites. You can apply these transitions to overlays, off-canvas menus, modals, and more.

Humans are instinctively compelled to follow motion and look for visual clues. It’s also been proven that motion makes a greater impact than static images, meaning we’re much more likely to remember content displayed through movement.

Motion UI is best used to tell a story and invoke emotion, making it a powerful tool in driving user engagement.

Tip: Looking for Motion design in UI inspiration? Check out these websites with great examples. Also, see this moving article for a Motion UI plugin you can use to make your WordPress sites jump.

Trends or Tools of the Trade?

We’ve been following trends like AI chatbots, voice assistants, PWAs, SPAs, IoT, and Motion UI for years; see how they’ve picked up steam since 2018, 2019,  and 2020.

2023 will witness a lot of advancements in the field of web development, and will transform the way the world does business – including the way you interact with your clients.

Adopting the latest web dev trends will allow you to stay competitive, by offering the most popular and cutting-edge designs and services.

If you are looking to build your WordPress sites on the sturdiest foundation, sign up for our newsletter to hear about the latest and greatest developments in the world of WordPress, and consider membership and hosting with WPMU DEV. With our suite of pro plugins, 5-star support, and a money-back guarantee, you’re sure to stay ahead of the curve.

]]>
https://wpmudev.com/blog/web-developer-trends/feed/ 21 2023-02-16T22:04:50Z
The Ultimate WordPress Local Development Cheat Sheet https://wpmudev.com/blog/wordpress-local-development-cheatsheet/ https://wpmudev.com/blog/wordpress-local-development-cheatsheet/#comments Tue, 14 Feb 2023 10:09:32 +0000 https://wpmudev.com/blog/?p=214551 Want to set up a local WordPress development environment without thumbing through pages and pages of documentation? Our WordPress local development cheat sheet will help you get up and running quick smart!

In this ‘no-fluff’ practical guide, we’ll cover briefly what WordPress local development is and some of the key benefits of using it, and we’ll then get straight into how to set up a local environment, install WordPress on your computer, and test your website before going live.

This guide covers the following:

What Is WordPress Local Development?

WordPress local development allows you to create a development environment for building, working, and testing WordPress sites on your computer without affecting your live site.

The local development environment replicates the production server, making it possible to test different scenarios and resolve issues before pushing changes to the live site.

Benefits of Local Development

Some of the key benefits of WordPress local development include:

  • Safe Testing Environment: The local development environment provides a safe space to test new features, plugins, and themes without affecting your live site.
  • Speed, Performance, and Efficiency: A local development environment is faster and more responsive than a remote server. This is because it runs on your computer, so your computer can access and process data much faster than a server, and there is no latency in communication between your machine and the server.
  • Cost-Effective: Setting up a local development environment eliminates the need for expensive hosting services and reduces the costs associated with deploying changes to a live site. You only need a computer and a text editor to get started.
  • Improved Collaboration: Multiple developers can work on a single project simultaneously without interfering with each other’s work.
  • Offline Development: With a local development environment, you can develop your site even when you’re offline.
  • Improved Security: Got a “top secret” project you want to work on? Since a local development environment runs on your machine, it is more secure than a remote server, so you can build and work on your site away from prying eyes. There is no risk of unauthorized access or hacking.

If you’re just getting started as a WordPress developer, see our introduction to WordPress local development article. If you’re already a little more experienced, check out our article on ways to improve your WordPress development workflow in a local environment.

Setting Up Your Local Development Environment

Before you can set up a local WordPress development environment, there are some things you’ll need.

What You’ll Need

In addition to a computer with enough storage space and processing power to support your development work, here’s all you need to set up a local development environment:

Local Server Software

You will need to install a local server software to run your local development environment.

XAMPP, MAMP, and WAMP are three popular options. Each of these local server software packages provide a complete development environment for web developers with all the necessary components (such as Apache web server, MySQL database, and PHP scripting language, in a single package), a control panel to manage these components and a tool to manage the database.

Each software package, however, also has its own unique features with key differences, so it’s important to choose one that meets your specific needs.

Let’s take a brief look at each:

XAMPP

XAMPP
XAMPP

XAMPP is a free, open-source, and easy-to-install web server software that provides a local development environment for web developers. It stands for Apache, MariaDB, PHP, and Perl, the four main components of XAMPP.

Some key features (and pros) of XAMPP:

  • Includes Apache web server, MariaDB database, and PHP and Perl scripting languages.
  • Supports multiple operating systems, including Windows, Mac, and Linux.
  • Easy-to-use control panel for managing web server and database components.
  • Option to install additional components such as phpMyAdmin for database management.

Cons:

  • Not as popular as MAMP or WAMP, so the community support may not be as strong.
  • More complex set-up compared to MAMP or WAMP, requiring more technical knowledge to install and configure components.

XAMPP is best for web developers who require a complete development environment with multiple components and are familiar with configuring and managing these components. It is also best for developers who work on multiple operating systems and need a cross-platform solution.

MAMP

MAMP
MAMP

MAMP is a local server software that provides a development environment for web developers. It stands for Macintosh, Apache, MySQL, and PHP, the four main components of MAMP.

Some key features (and pros) of MAMP:

  • Includes Apache web server, MySQL database, and PHP scripting language.
  • Supported by macOS operating system, but can also be used for Windows-based OS.
  • Easy-to-use control panel for managing web server and database components.
  • Option to install additional components such as phpMyAdmin for database management.

Cons:

  • Can only use PHP scripting language.
  • Fewer components compared to XAMPP, which may limit some developers’ needs.

MAMP is best for web developers who work on the macOS operating system.

For more information on using this option, check out our tutorial on how to develop WordPress locally using MAMP.

WampServer

WampServer
WampServer

WAMP is a local server software that provides a development environment for web developers. It stands for Windows, Apache, MySQL, and PHP, the four main components of WAMP.

Some key features (and pros) of WAMP:

  • Includes Apache web server, MySQL database, and PHP scripting language.
  • Supports Windows operating system.
  • Easy-to-use control panel for managing web server and database components.
  • Option to install additional components such as phpMyAdmin for database management.

Cons:

  • Only supports Windows, so developers using macOS or Linux may need to look elsewhere.
  • Fewer components compared to XAMPP, which may limit some developers’ needs.

WAMP is best for web developers who work on the Windows operating system and who require a complete development environment with basic components.

For more information about this option, check out our tutorial on how to develop WordPress locally using WAMP.

While XAMPP, MAMP, and WAMP are all excellent choices for web developers looking for a local development environment, there are other options available, including Local by Flywheel, AMPPS (Windows & MacOS), Laragon (Windows only), and (if you need to work on WordPress locally on more than one machine) even installing and running WordPress from a USB.

Text Editor

The other component you’ll need is a text editor for WordPress development specifically designed for working with programming languages such as PHP. A text editor is essential for editing code and making changes to your website.

Let’s look at a couple of popular options for text editors:

Sublime Text

Sublime Text
Sublime Text

Sublime Text is a popular text editor that is widely used by developers for coding and scripting purposes. It offers a clean, fast and intuitive interface, making it easy to work with large codebases.

Some key features of Sublime Text:

  • Syntax highlighting and code completion for over 80 programming languages
  • Customizable color schemes, key bindings, and macros
  • Advanced searching and editing tools such as multiple selections, split editing, and column editing
  • Instantly switch between projects with a project-specific settings system

Sublime Text is a great tool for developers who work on projects that require writing code in HTML, CSS, and JavaScript. It offers easy-to-use syntax highlighting, code completion, and editing tools that make the coding process fast and efficient.

Visual Studio Code

Visual Studio Code
Visual Studio Code

Visual Studio Code is a free, open-source code editor developed by Microsoft. It offers a range of features and tools to help developers create and manage large-scale projects.

Some key features of Visual Studio Code:

  • IntelliSense, a smart and advanced code completion and debugging tool
  • Built-in Git support and debugging
  • Supports multiple programming languages and has a large library of extensions
  • Customizable interface and workspace

For additional text editors, see our list of the best text editors for WordPress development.

Have you ticked all of the above requirements?

  • Computer meets required specs
  • Selected local server software
  • Selected text editor

Great! Then let’s move on to the next step…

Installing Local Server Software

For this example, we’ll install XAMPP on a Windows operating system. Use the same process described below to install your chosen local server software on your computer and follow the software package’s specific instructions:

  1. Download XAMPP: Go to the XAMPP official website and download the latest version of XAMPP for Windows.
  2. Install XAMPP: Double-click the downloaded file to start the installation process. Run the downloaded installer file and follow the on-screen instructions to install XAMPP. By default, XAMPP will be installed in the C:\xampp directory.
  3. Start XAMPP: After installation, open the XAMPP Control Panel from the Start menu or desktop shortcut. Start the Apache and MySQL modules by clicking on the “Start” buttons next to each module.
  4. Verify installation: To verify that XAMPP is working correctly, open a web browser and navigate to http://localhost. This should display the XAMPP welcome page.
  5. Create a virtual host: To create a virtual host, follow the steps outlined below.

XAMPP should now be installed and configured on your machine. You’re ready to start developing and testing your websites locally.

Note: The process of installing XAMPP or other local server software, such as MAMP or WAMP, may vary slightly depending on the operating system being used. For Mac and Linux operating systems, you can follow the installation instructions provided on the XAMPP website.

See our other XAMPP-related tutorials for additional information on setting up XAMPP, upgrading XAMPP, troubleshooting XAMPP, and migrating WordPress from a XAMPP localhost to the web.

Setting Up a Virtual Host

Setting up a virtual host in a local development environment allows developers to run multiple websites on their local machine, each with its own unique URL. This provides a more realistic testing environment and makes it easier to switch between different projects.

For the step-by-step guide below to set up a virtual host in your local development environment and start testing your websites:

1. Open the Apache configuration file: Open the configuration file for your local server software. For this example, we’re using XAMPP, so open the Apache configuration file, typically located at /etc/httpd/conf/httpd.conf or C:\xampp\apache\conf\httpd.conf.

2. Enable virtual hosting: Locate the section labeled “# Virtual Hosts” and uncomment the following line by removing the hash symbol (#) at the beginning of the line: #Include conf/extra/httpd-vhosts.conf.

3. Configure the virtual host: Open the virtual host configuration file, typically located at /etc/httpd/conf/extra/httpd-vhosts.conf or C:\xampp\apache\conf\extra\httpd-vhosts.conf.

4. Add a new virtual host: Add a new virtual host by creating a new block of code with the following format:

ServerName example.local
DocumentRoot "/path/to/document/root"
<Directory "/path/to/document/root">
AllowOverride All
Require all granted

Do this:

  • Replace “example.local” with the desired URL for the virtual host.
  • Replace “/path/to/document/root” with the full path to the document root directory for the virtual host.

5. Update the hosts file: The hosts file maps domain names to IP addresses. To make the virtual host accessible via the URL you specified, you’ll need to add an entry to the hosts file. The hosts file is typically located at /etc/hosts or C:\Windows\System32\drivers\etc\hosts. Add a new line with the following format: 127.0.0.1 example.local. Replace “example.local” with the URL specified in the virtual host configuration. Save the changes to the configuration file.

6. Restart Apache: Restart the Apache local web server to apply the changes.

7. Test the virtual host: Test your virtual host by visiting the URL in a web browser. The browser should display the content of the document root directory for the virtual host.

Creating a Database for Your Local WordPress Installation

The next step before setting up a WordPress project locally is to create a database for your local development environment.

Follow these step-by-step instructions to create a database in XAMPP:

1. Open the XAMPP Control Panel: Open the XAMPP Control Panel from the Start menu or desktop shortcut. Make sure the Apache and MySQL modules are running.

2. Access phpMyAdmin: To access phpMyAdmin, open a web browser and navigate to http://localhost/phpmyadmin. This will open the phpMyAdmin interface in your browser.

3. Create a new database: In the phpMyAdmin interface, click on the “Databases” tab. In the “Create database” section, enter a name for your new database and select the “utf8mb4_general_ci” collation. Then, click on the “Create” button.

4. Create a new user: To create a new user for the database, click on the “Users” tab and then the “Add user” button. In the “Add user” form, enter a username and password for the new user, and select “Local” as the host. Make sure to grant all privileges to the user by checking the “Grant all privileges on database” checkbox. Finally, click on the “Go” button.

5. Save your details: Write down or save your database name, username and password. You will need these to connect the database to WordPress later.

After completing the above steps, you will have successfully created a database for your local WordPress installation and local development environment.

You can now use this database to store and manage your data as you develop and test your WordPress site locally.

Have you completed all of the above steps?

  • Installed local server software
  • Set up virtual host
  • Created database

Great! Then let’s move on to the next step…

Installing WordPress Locally

Now that we have prepared our local environment, the next step is to download, install, and configure WordPress.

Downloading and Installing WordPress on Local Server

Follow the steps below to complete this process:

  1. Visit the WordPress website: Go to the official WordPress.org website and click on the “Download WordPress” button to download the latest version of WordPress.
  2. Extract the archive: The WordPress download will be a compressed ZIP file. Extract the contents of the archive to a directory on your computer.
  3. Move the extracted files to your local server: Move the contents of the extracted directory to the root directory of your local server. If you’re using XAMPP, for example, this is typically C:\xampp\htdocs on Windows or /Applications/XAMPP/htdocs on macOS.
  4. Create a database: (Note: if you have been following along, this step should already be done.) Before installing WordPress, you’ll need to create a database. You can do this using a tool like phpMyAdmin, which is included with most local server software like XAMPP and MAMP.
  5. Start the installation: Open your web browser and navigate to http://localhost/wordpress (or the equivalent URL for your local server). This will start the WordPress installation process.
  6. Choose the language: On the first screen, select your preferred language and click the “Continue” button.
  7. Fill in the database information: On the next screen, fill in the database information that you created in step 4. This includes the database name, database username, and database password.
  8. Fill in the site information: On the next screen, fill in the information for your local WordPress site. This includes the site title, username, password, and email address.
  9. Run the installation: Once you’ve filled in all the information, click the “Install WordPress” button to run the installation.
  10. Log in to your site: After the installation is complete, log in to your local WordPress site using the username and password you created in step 8 to start customizing and developing your local site.

You have now successfully downloaded and installed WordPress.

You can now start customizing and developing your site locally, with all the benefits of a local development environment, before deploying your site to a live server.

Configuring wp-config.php File

The wp-config.php file is a crucial component in the setup of a local WordPress installation and local development environment. This file contains configuration settings that control how WordPress interacts with your database and other important settings.

If you have followed the installation instructions above, your database credentials will be automatically added to the wp-config.php file.

If, for any reason, you need to manually configure the wp-config.php file, follow the instructions below:

1. Create a wp-config.php file: If your local WordPress installation doesn’t already have a wp-config.php file, you can create one by copying the wp-config-sample.php file and renaming it to wp-config.php.

2. Update database credentials: Open the wp-config.php file and update the following lines with the appropriate information:

define( 'DB_NAME', 'database_name' );
define( 'DB_USER', 'database_user' );
define( 'DB_PASSWORD', 'database_password' );
define( 'DB_HOST', 'localhost' );

Replace database_name, database_user, and database_password with the values you used when creating the database and user in a previous step.

3. Set the WordPress security keys: WordPress security keys add an extra layer of security to your site by encrypting information stored in cookies. You can generate a set of security keys at the official WordPress site. Copy the generated keys and paste them into your wp-config.php file, replacing the placeholder keys that are already there.

4. Enable debugging: For local development, it’s useful to enable debugging in WordPress. This will provide more detailed error messages and warnings that can help you troubleshoot issues with your site. To enable debugging, add the following line to your wp-config.php file:

define( 'WP_DEBUG', true );

5. Save the changes: Once you have made the changes to the wp-config.php file, save the file and close it.

Successfully configuring the wp-config.php file will ensure that your locally installed WordPress site is able to connect to the database, is secure, and provides helpful debugging information as you develop and test your site locally.

Importing a Live WordPress Site to Local Environment

Follow the steps below if you need to import a live WordPress site into your local environment:

Exporting the Live Site’s Database

To export the live site’s database, you’ll need to have access to the live site’s server.

Here are the steps to export the live site’s database (note: different server environments will perform this differently, but most should follow a similar process):

  1. Log into your live server’s control panel.
  2. Access the database: The first step is to access the database of the live site. You can do this using a tool like phpMyAdmin, which is often provided by your web hosting provider. Look for a section called “Databases” and click on “phpMyAdmin.”
  3. Select the database: Once you’ve logged into phpMyAdmin, select the database for your live site from the left-side panel.
  4. Export the database: Click on the “Export” button to start the export process.
  5. Choose the export format: On the export screen, choose the “Quick” export method, select the “SQL” format and make sure that the “Structure” and “Data” options are selected.
  6. Download the export file: Click the “Go” button to download the export file to your computer.

Importing the Database to the Local Server

To import the live site’s database to your local server, make sure your chosen local server software is already installed on your computer.

Here are the steps to import the live site’s database to your local server:

  1. Open phpMyAdmin in your local server software: Log into phpMyAdmin for your local server and select the database you created for your local WordPress installation.
  2. Import the database: Click on the “Import” button to import the data from the export file you just downloaded.
  3. Select the import file: On the import screen, click on the “Choose File” button, select the export file you just downloaded, and click the “Go” button to start the import process.

Replacing URLs in the Database

After importing the live site’s database, you will need to replace the URLs in the database to match your local development environment.

Here are the steps to replace URLs in the database:

1. Open phpMyAdmin in your local server software.
2. Select the imported database from the left-side panel.
3. Click on the “SQL” tab.
4. Enter the following query in the text area:

UPDATE wp_options SET option_value = replace(option_value, 'http://www.livesite.com', 'http://local.livesite.com') WHERE option_name = 'home' OR option_name = 'siteurl';
UPDATE wp_posts SET guid = replace(guid, 'http://www.livesite.com','http://local.livesite.com');
UPDATE wp_posts SET post_content = replace(post_content, 'http://www.livesite.com', 'http://local.livesite.com');

5. Replace “http://www.livesite.com” with the URL of your live site, and replace “http://local.livesite.com” with the URL of your local development environment.

6. Click on the “Go” button to execute the query.

Uploading the Live Site’s Files to the Local Environment

To upload the live site’s files to the local environment, you will need to have FTP access to your live site’s server.

Follow the steps below to upload the live site’s files to your local environment:

  1. Connect to your live site’s server using an FTP client such as FileZilla.
  2. Navigate to the root directory of your live site on the server.
  3. Download all the files to your local computer.
  4. Place the downloaded files in the root directory of your local development environment, which is usually located in the “htdocs” or “www” folder in XAMPP or other local server software.

Notes:

  1. If you already have a WordPress installation, the above folder won’t be empty and you will be prompted to replace existing files and directories, so replace all files except for the wp-config.php file to keep the same configurations, including the connected databases which have been populated with the live site’s data.
  2. Before uploading the live site’s files to the local environment, you may need to change the file permissions to make the files writable by your local server software.
  3. Also, make sure to test your local WordPress backup before making any changes.

That’s it! You have now successfully imported your live site into your local WordPress installation and local development environment.

Developing and Testing on Local WordPress Site

You’re finally ready to develop and test your site locally using the same data as your live site, giving you a true-to-life environment for testing and development.

Let’s go through the process:

Making Changes and Testing

  1. Log into the local WordPress site: Open your local WordPress site in your web browser and log in to the WordPress dashboard using your administrator credentials.
  2. Make changes to the site: You can make changes to your local WordPress site by editing themes, plugins, or custom code. Simply access these elements from the WordPress dashboard.
  3. Test changes: After making changes to your local WordPress site, it’s important to test the changes to make sure they work as expected. You can test changes by visiting the front-end of your site and checking that the changes have taken effect.

Debugging

  1. Use the Debugging mode: WordPress has a built-in debugging mode that makes it easier to identify and resolve issues on your site. To enable the debugging mode, you need to add the following code to your wp-config.php file: define( 'WP_DEBUG', true );.
  2. Check the error logs: If you’re having issues with your local WordPress site, you can check the error logs to see if there are any error messages or warning messages that can help you identify the issue. The error logs can be found in the WordPress debug log file, which is located in the wp-content directory.
  3. Use debugging tools: There are a number of debugging tools and plugins available for WordPress that can help you identify and resolve issues on your site. For example, the Query Monitor plugin provides detailed information about database queries, plugin usage, and more. See this tutorial for help with debugging WordPress: Debugging WordPress: How To Use WP_Debug

Testing Different Plugins and Themes

Installing, activating, and testing plugins and themes on a local WordPress site works in exactly the same way as it does on any other regular WordPress site. So, make sure to do the following while in testing mode:

  1. Install plugins: Install plugins on your local WordPress site to add new features or functionality to your site. To install a plugin, log in to the WordPress dashboard, go to the Plugins section, and click on the Add New button.
  2. Activate plugins: Activate the plugin you’re testing after installing it to use it on your site. To activate a plugin, go to the Plugins section of the WordPress dashboard and click on the Activate button next to the plugin you want to use.
  3. Test plugins: After activating a plugin, it’s important to test the plugin to make sure it’s working as expected. Test plugins by visiting the front-end of your site and checking that the plugin has taken effect.
  4. Install themes: Install themes on your local WordPress site to change the appearance of your site. To install a theme, log in to the WordPress dashboard, go to the Appearance section, and click on the Themes button.
  5. Activate themes: Activate the theme after installing it to change your site’s appearance. To activate a theme, go to the Appearance section of the WordPress dashboard and click on the Activate button next to the theme you want to use.
  6. Test themes: After activating a theme, it’s important to test the theme to make sure it’s working as expected. Test themes by visiting the front-end of your site and checking that the theme has taken effect.

Have you make all the changes you need, debugged issues, and tested different plugins and themes on your local site?

Great! Now you’re ready to make your local WordPress site live.

Deploying Local WordPress Site to Live Server

The final step in this process is to export all of your local WordPress files and database to your live hosting environment and make sure that all of your site’s changes, configurations, and URLs are working on your live site.

Exporting the Local Site’s Database

Follow the steps below to export your local WordPress site to your live server:

  1. Log in to the local site’s database using PHPMyAdmin.
  2. Select the database you want to export.
  3. Go to the “Export” tab.
  4. Choose the “Quick” export method.
  5. Select the “SQL” format.
  6. Click “Go” to download the SQL file to your computer.

Importing the Database to the Live Server

Follow the steps below to import your local WordPress database’s export file into your live site:

  1. Log in to the live server’s database using PHPMyAdmin.
  2. Create a new database for the live site.
  3. Go to the new database and select the “Import” tab.
  4. Choose the exported SQL file from your local site.
  5. Click “Go” to import the database.

Now that you have migrated the database over from your local site to your live site, let’s do the same for your site’s files.

Uploading the Local Site’s Files to the Live Server

Follow the steps below to upload your local WordPress site’s files into your live site:

  1. Prepare the files: Before uploading the local site’s files to the server, it’s a good idea to review and clean up the files. This may include removing any unnecessary files, such as backups or test files, to minimize the amount of data being uploaded.
  2. Connect to the server: You can connect to the server using a variety of methods, such as FTP or SFTP. You will need to use a client software, such as FileZilla, to connect to the server. You will need to provide your server host, username, and password to connect.
  3. Upload the files: Once you are connected to the server, you can upload the local site’s files to the server. You can upload the files in a number of ways, including uploading individual files or uploading the entire local site folder. Navigate to the root directory of the live site on the server. Upload all the local site’s files to the live site’s directory on the server, and replace the existing files if prompted.
  4. Update the database information: After uploading the files to the server, you will need to update the database information in the wp-config.php file to reflect the live site’s database information. Open the wp-config.php file in a text editor and update the database name, username, and password to match the live database.
  5. Update URLs in the database:  See the section below.
  6. Test the site: After uploading the local site’s files to the server, it’s a good idea to test the site to make sure everything is working correctly. This may involve testing the site’s functionality, links, and images to make sure they are working as expected.

Updating URLs in the database

You can update the URLs in your database using a text editor or by working directly in your database (make sure your database is fully backed up before making changes).

Updating URLs Using a Text Editor

Follow the steps below to update the URLs in your database using a text editor.

  1. Export the database: Before updating the URLs in the database, you will need to export the database. Use your database management tool (e.g. phpMyAdmin).
  2. Find and Replace the URLs: Once you have exported the database, you will need to find and replace the URLs in the database. You can do this using a text editor such as Sublime or Visual Studio Code. Search and replace the URLs, and make sure to replace the URLs carefully and thoroughly, including URLs in serialized data.
  3. Import the database: After updating the URLs in the database, you will need to import the database back into your local development environment. You can import the database using a database management tool, such as phpMyAdmin.
  4. Test the site: After importing the updated database, it’s a good idea to test the site to make sure everything is working correctly. This may involve testing the site’s functionality, links, and images to make sure they are working as expected.

Updating URLs in the Database

Follow the steps below to update the URLs directly in your database:

1. Log in to the live site’s database using PHPMyAdmin.
2. Select the live site’s database.
3. Go to the “SQL” tab.
4. Run the following SQL query to update the URLs:

UPDATE wp_options SET option_value = replace(option_value, 'http://old-url', 'http://new-url') WHERE option_name = 'home' OR option_name = 'siteurl';
UPDATE wp_posts SET guid = replace(guid, 'http://old-url','http://new-url');
UPDATE wp_posts SET post_content = replace(post_content, 'http://old-url', 'http://new-url');

Replace “old-url” with the URL of the local site and “new-url” with the URL of the live site.

5. Click “Go” to run the query.
6. This will update all references to the local site’s URL with the live site’s URL in the database, ensuring that all links and images on the live site work correctly.

If you have followed the above steps correctly, the URLs in your database should have successfully updated. After these steps, your local WordPress site should now be fully functional on the live server. Make sure to thoroughly test the live site to ensure that all features are working correctly, and make any necessary adjustments to ensure a seamless transition from the local development environment to the live server.

Local Development vs Webhost Staging Environment

While WordPress local development provides a safe and efficient environment to build, edit, and test WordPress websites, you may decide to work in a webhost staging environment instead (here are some good reasons why you may not want to develop WordPress locally).

Both local development environments and webhost staging environments, however, have their pros and cons.

Here is a brief overview of the pros and cons of using a WordPress local development versus a webhost staging environment:

Pros of Local Development Environment

  • Easy to Use: Local development environments are easy to use, even for beginner developers.
  • Flexibility: You have complete control over your local development environment, so you can configure it however you like.
  • Test Any Changes: With a local development environment, you can test any changes you make to your site without affecting the live version.

Cons of Local Development Environment

  • Not a Live Environment: A local development environment is not a live environment, so you cannot test your site with live data.
  • Limited Resources: Your local machine may have limited resources, such as memory and processing power, which can affect your site’s performance.
  • Not a True Representation: A local development environment may not accurately represent a live server environment, so testing may not be 100% accurate.

Pros of Webhost Staging Environment

  • Live Environment: A webhost staging environment is a live environment, so you can test your site with live data.
  • More Accurate Testing: A webhost staging environment is a more accurate representation of a live server environment, so testing is more reliable.
  • More Resources: A webhost staging environment typically has more resources available than a local development environment, so your site’s performance will be better.

Cons of Webhost Staging Environment

  • Cost: Setting up a webhost staging environment can be expensive, as you have to pay for hosting and a domain name.
  • Not as Fast: A webhost staging environment is not as fast as a local development environment because it runs on a remote server.

For smaller projects, a local development environment is a great option because it is free and easy to use. For larger projects, however, a webhost staging environment may be a better option because it is a live environment and provides more accurate testing.

Ultimately, the choice between these two methods will depend on your individual needs, preferences, and hosting options.

Note: We recommend avoiding shared hosting, and hosting on our Quantum plan instead for basic WordPress sites, but if you have reasons for choosing shared hosting, then check out our article on how to run WordPress local development on shared hosting.

All WPMU DEV hosting plans (except for Quantum) include a staging environment. Refer to our staging documentation for more details on the benefits of using a staging environment to develop and test WordPress sites.

]]>
https://wpmudev.com/blog/wordpress-local-development-cheatsheet/feed/ 18 2023-02-14T10:09:32Z
How to Improve First Contentful and Meaningful Paint https://wpmudev.com/blog/improve-first-contentful-meaningful-paint/ https://wpmudev.com/blog/improve-first-contentful-meaningful-paint/#comments Sun, 30 Jan 2022 09:00:10 +0000 https://premium.wpmudev.org/blog/?p=176123 You’re not optimizing your site to please a stopwatch. You’re optimizing your site for real people. So how can you determine if you’re achieving your goal?

You need to include metrics such as First Contentful Paint and First Meaningful Paint in your performance assessment in order to measure how your site is performing from your user’s perspective. Both will tell you more about how your site is behaving in the wild so you can optimize the things that will really improve your user’s experience.

In this post, we’re going to focus specifically on how to reduce the amount of time it takes to load content on your WordPress site so you can shorten the amount of time to the First Contentful Paint and First Meaningful Paint and improve your Google PageSpeed Insights score in the process.

Here’s everything you need to know about the First Contentful Paint & First Meaningful Paint, and how to improve them:

What is First Contentful Paint (FCP)?

First Contentful Paint, or FCP, is a performance metric that measures how much time has elapsed before the browser begins to display the first elements of the site.

Usually, the first content paint elements in WordPress are header elements, so the visitor will first see the site logo or the navigational menu.

Screenshot of WPMU DEV blog page half loaded
Here’s an example of the First Contentful Paint usually looks like. We’re still waiting for the content to show up.

The First Contentful Paint is important because it provides the visitor with feedback that their request is in the works. Have you ever clicked on a link or a button and then clicked it a couple more times because nothing happened? The FCP’s job is to communicate “we heard you and we’re working on it.” This assures the reader that they can expect your site to function correctly and provide content.

What is First Meaningful Paint (FMP)?

First Meaningful Paint is when the good stuff actually loads. When the content the user is looking for appears on the page, this is referred to as the first meaningful paint.

Screenshot of WPMU DEV Blog page fully loaded
An example of what the First Meaningful Paint looks like, the hero image and intro text has loaded so I can start reading
Screenshot of WPMU DEV blog images haven't finished loading
But if I scroll down right away to show you, you can see that page hasn’t finished loading, the images are still missing. But who cares? The user will probably not scroll down so fast, they’ll start to read through your content while the rest of the page finishes loading.

Visitors come to your site for content, not to see the logo and navigation menu, so the content holds more value for the visitor. The first meaningful paint is one of the most important metrics for evaluating how long your visitor is waiting to receive the information they visited your site for. The first meaningful paint also includes the time it takes to load web fonts since they’re needed to render your content.

The most valuable content elements on your web page are known as hero elements. This varies from site-to-site, but it isn’t hard to determine what the most valuable part of a page is.

For video pages on YouTube, the most important element is the video. On social networks, the first posts in the timeline that are above the fold are the most important. For blogs, the body of the blog post and the featured image (if it is featured above the fold with the blog content) are the most important because this is what the visitor sees first.

Other content, such as images, can be deferred until the visitor needs them.

Using Google PageSpeed Insights to Find FCP and FMP

Both First Contentful Paint and First Meaningful Paint are known as user-centric performance metrics. Google rewards sites that deliver a better user experience with higher search rankings. Since Google wants to encourage site owners to optimize their sites for users, FCP and FMP are two metrics that are measured in Google PageSpeed Insights.

Screenshot of Lab Data in Google PageSpeed Insights
You can also see a timeline of what your site looks as it loads. Can you tell which is the first contentful and meaningful paint?

Since November 2018, Google PageSpeed Insights has started using an open source tool called Lighthouse to simulate how your site loads for visitors. Lighthouse returns 6 metrics in the Lab Data section, that paint a rich picture of your site’s performance:

  • First Contentful Paint
  • Speed Index
  • Time to Interactive
  • First Meaningful Paint
  • First CPU Idle
  • Estimated Input Latency

First Contentful Paint and the First Meaningful Paint are time-based metrics that are measured in seconds. To achieve a favorable score in the eyes of Google, you want both the FMP and the FCP to be less than a second.

5 Recommendations for Reducing Paint Times and Improving Your PageSpeed Insights Score

When you run Google PageSpeed Insights, Google provides you with tailored suggestions on how you can fix your site. Running a test is the best way to see how your site falling short.

The following five suggestions are straight from Google for all sites on how to improve first meaningful paint and how to improve first contentful paint.

Our goal with the first four recommendations is to improve First Contentful Paint by speeding up the time it takes to download resources and remove obstacles that block the browser from registering DOM content. The last suggestion is to improve the First Meaningful Paint.

We’re about to get into some techy details, but if you want a simple solution, Hummingbird can help. Try Hummingbird Pro free and see what a difference it makes for your site. Version 3.0 is now available to our members with an all-new scanner that includes Lighthouse recommendations.

Contentful Paint Recommendations in Hummingbird
Contentful Paint, Meaningful Paint, and one-click fixes now included in Hummingbird Pro.

And for our WordPress.org Hummingbird free users, you can expect to see the new scanner sometime next week… or upgrade to pro and get it now ;)

1. “Minimize the number of render-blocking external stylesheets and scripts upon which the page depends”

What is render blocking? When a visitor is loading a webpage, anything that is getting in the way of rendering the DOM is referred to as render-blocking. They’re code obstacles that the browser has to process first before it can do anything else.

Sometimes they’re important. Your CSS files, for instance, are render-blocking, but they’re critical.

Other times, the render-blocking resource can wait. This is why you should move JavaScript files from the header of your webpage if they’re not needed to render the DOM. Load them after the DOM to improve user experience.

If you can, the best way to optimize page speed is to eliminate render-blocking resources altogether. If they don’t spark joy, then byeeeee….

2. “Use HTTP Caching to speed up repeat visits”

Caching is a reliable way to improve site speed for your visitors by storing assets in a cache for faster retrieval. There are several kinds of caches.

With HTTP caching, the browser stores a copy of assets downloaded via HTTP by the user in its cache, so it will be able to retrieve them without making an additional trip to the server. This dramatically improves performance for repeat visitors when done properly.

We recently compared Hummingbird to other popular caching plugins and Hummingbird out optimized all of them.

3. “Minify and compress text-based assets to speed up their download time”

Your webpages consist of text-based HTML, CSS and JavaScript files. If you can’t eliminate a file because it is essential, then you need to reduce the file size as much as possible.

There are two ways to do this:

Minify your files
When you minify your text files, you remove all extraneous characters and spaces, creating a compacted file that is much more difficult for humans to read, but much smaller. The browser doesn’t mind the lack of readability and will be able to download the file much more quickly.

Compress your files
Compressing your files is similar to the process of compressing your images. During the compression process, the compressor detects patterns and duplication in the text file and encodes them much more efficiently.

Both minifying and compressing your text files removes extra bytes that don’t affect your webpage negatively but reduces paint times.

4. “Do less JavaScript work on page load”

JavaScript is one of the worst offenders when it comes to slowing down your site. For one, JavaScript files take more resources to process when compared to other assets. Images, for instance, must be decoded, but JavaScript must be parsed, compiled, and then finally executed, taking up lots of valuable time.

It also doesn’t help when JavaScript code is rolled together into one huge file. I know that feels counterintuitive, but creating one big file doesn’t help performance one bit.

You’re much better off splitting up your code into bite-sized chunks with a process known as code-splitting. Then you can move the chunks that aren’t critical out of the head of your site, reducing the first paint time.

Another way to minimize your JavaScript files is to prune out code that is no longer being used. This process is known as tree shaking. As your site matures, you add in snippets of code, but not all of it is used in the long term. You should periodically go through your JavaScript code and remove what you don’t need.

5. “Optimizing the Critical Rendering Path to achieve a faster First Meaningful Paint”

The critical rendering path refers to all of the assets that the browser needs to render to respond to the visitor’s current request. You want to prioritize the assets that are most important right now and load them as quickly as possible

It’s like traveling. If you need to get to an appointment on time and you’re running late, it’s probably not the best time to run quick errands or do a little sightseeing. Do that after!

This recommendation encompasses removing render-blocking resources, but it takes a broader perspective. You need to look at all of the work that the browser is doing to deliver the webpage and find a better way to serve the important bits and put off everything that can wait. If it isn’t critical then you can defer it or load it asynchronously in order to deliver a better performance.

Keep in Mind

As you start to optimize your site, it is important that you remember that the results returned by Google PageSpeed Insights only represents a single perspective. They’re simulated results, but they don’t fully capture reality.

Visitors who are visiting your site on crappy devices on a shoddy mobile connection will experience FCP and FMP that are much much longer. All the more reason to continue improving even if you get a perfect 100.

Your goal should always be to optimize your site for real users, not a gold star ;)

Summary

First Contentful Paint and First Meaningful Paint are user-centered metrics that can tell you a lot about how long your visitors are waiting for content. Both should be less than a second for the best user experience. You can find out how your site scores with Google PageSpeed Insights.

If your site is too slow, the best way to improve time to first paint is to minimize render-blocking resources, use HTTP caching, minify and compress text-based assets, do less JavaScript work and optimize the critical rendering path. If you’re not sure what you need to do, running a Google PageSpeed Insights test will give you targeted suggestions for your site.

If you’re not sure how to improve your paint times, Hummingbird makes it easy. Get Hummingbird free on WordPress.org or try Hummingbird Pro free.

]]>
https://wpmudev.com/blog/improve-first-contentful-meaningful-paint/feed/ 22 2022-01-30T09:00:10Z
Handling Form Submissions in WordPress with Admin-Post and Admin-Ajax https://wpmudev.com/blog/handling-form-submissions/ https://wpmudev.com/blog/handling-form-submissions/#comments Mon, 17 Jan 2022 13:00:49 +0000 https://premium.wpmudev.org/blog/?p=167713 WordPress provides incredible support for you to work with form submissions in your application. Whether you add a form in the admin or public facing areas, the built-in mechanism with the admin-post and admin-ajax scripts will allow you to handle your form requests efficiently.

In this article, I’ll show you how to handle custom form submissions using the WordPress API. I’ll walk you through the process of adding a custom form in the admin area of a plugin, handle the form submission via an HTML as well as an AJAX request, and write the form handler in PHP to validate, sanitize and process the form input.

While I’ll stay within the admin realms of WordPress, the same concepts are applicable while working with forms in the public facing areas.

I’ll also be making use of object-oriented programming constructs for the plugin; however, you can achieve the same result using procedural code as well. The practice plugin can be downloaded from here to follow along with the article.

Note: This article is intended for intermediate-advanced WordPress developers. It assumes that you have a working knowledge of HTML, JavaScript, jQuery, PHP and the WordPress Plugin API. If you’d like a refresher, I recommend that you read through the following:

Let’s get started by first understanding the built-in WordPress mechanism to handle a regular form post request.

Form Submissions with admin-post.php in WordPress

The gamut of hooks available in WordPress gives you great control over the flow of execution of your application. This is no different when it comes to processing forms. All you need is the correct hook to ‘hook into’ and add the custom form handler. The hooks for processing custom forms are dynamic in nature, meaning that the name of the hook partly depends on you.

To process submissions related to your form only, you need finer control as shown below:

WordPress form submission with admin-post.php
WordPress form submission with admin-post.php.

This is done by pointing the form submission to the admin-post.php file located in the wp-admin directory of WordPress, and including a custom name for the action in the form. On doing so, WordPress will trigger two action hooks based on the logged in status of the user:

  • admin_post_{$action} for logged in users
  • admin_post_nopriv_{$action} for non-logged in users

Where $action is the name of the action that was passed through the form.

You can then use add_action to tie the PHP form handler to the triggered hooks, where you will have full control to process the form data with the $_GET and $_POST variables.

As you may have guessed already, despite its name, admin-post.php can handle POST and GET requests as well as requests for admin and non-admin areas of the application.

Let’s explore this with the help of a custom plugin.

The Object-Oriented Plugin Structure

My goal here is to help you understand everything that goes behind processing custom forms in WordPress with and without AJAX. For this article, I’ve prepared a custom plugin that you can download from here to follow along. I recommend that you have it open in a suitable editor and install it on a local WordPress setup only.

I built the plugin using object-oriented programming practices with the help of a plugin boilerplate. Boilerplate Starting Points are among the many best practices listed in the WordPress Plugin Handbook. They’re a great way to ensure consistency across your plugins, and save you a lot of time writing standard code. Over a period, you may even end up writing your own custom boilerplate based on your coding preferences. That’s what I did.

The plugin is based on my own plugin template which is a fork of the original WordPress Plugin Boilerplate project. It’s similar to the original project in many aspects but also has support for namespaces and autoloading. This way I don’t need to have unique prefixes for every class or function, and don’t end up with a lot of include and require statements. However, the minimum required PHP version for my plugin is 5.6.0.

Note: If you don’t use namespaces or use procedural code you must prefix everything.

Here’s how the plugin is structured in the backend:

  • inc/core/* – core functionality of the plugin
  • inc/admin/* – functionality related with the admin area
  • inc/frontend/* – functionality related with the public facing areas
  • inc/common/* – functionality shared between the admin and the frontend
oop-based-plugin structure
Plugin structure in the backend.

The plugin has a top-level admin menu with two menu items for the form pages.

admin menu structure of the plugin
Admin menu structure of the plugin.

To see how I added the admin menu pages, take a look at the define_admin_hooks() method in inc/core/class-init.php and the add_plugin_admin_menu() method in the inc/admin/class-admin.php of the plugin.

If you’d like to know more about adding admin pages to your plugin, have a look at our article about creating WordPress admin pages here.

Adding the Form to the Admin Page of the Plugin

When I added the “HTML Form Submit” menu page for the plugin, I had to also specify the callback to load the page content. This is where the form is added.

However, instead of directly writing the HTML in the html_form_page_content method, I used another file partials-html-form-view.phplocated in inc/admin/views for the form HTML and loaded it in the callback as shown below:

This is purely a coding preference. It allows me to keep my code readable by separating the HTML, and makes no difference to the output of the form on the plugin page.

plugin admin page with html form
HTML Form in the admin page of the plugin.

Understanding Form Security, Structure, and Submission

The form that was added above has a select field with a drop-down list of existing WordPress users and two text fields for user input. However, this simple example has a lot going on behind the scenes. The form code below is self-explanatory, so let’s walk through the important elements:

Form Security

The most important thing to keep in mind when dealing with forms in the admin area of WordPress is security. Secure your form using a combination of both WordPress Nonces and current_user_can( $capability ). In my example, I’ve restricted entry to the form with if( current_user_can( 'edit_users' ) ), i.e. the form will be loaded only if the logged in user has the edit_users capability.

I also generated a custom nonce by using wp_create_nonce() and then added it as a hidden form field. You can instead use wp_nonce_field() to add it directly. Here’s a great article to understand Nonces in detail.

Form Structure

I’ve prefixed all form elements with the plugin name to ensure uniqueness. This is again a personal coding preference, as I can be sure of targeting only my form elements through JavaScript. I’ve also used the HTML5 required attribute to leave form validation to the browser.

plugin form inspect view in chrome
Inspecting the admin form.

Form Submission

The form submission is made to the admin-post.php using the admin_url( 'admin-post.php' ) function rather than hardcoding the URL. When WordPress receives the form, it will look for the value of the action field to trigger the form hooks. In my case, it will generate the admin_post_nds_form_response hook. Had it been a page open to the public view, it would have triggered the admin_post_nopriv_nds_form_response hook.

The Form Handler for the POST request

At this stage, if you submit the form, you’ll be redirected to an empty page with the page URL set to the admin-post.php. This is because there is no form handler to process the request yet. To process the request, I registered my custom handler the_form_response in the define_admin_hooks() method of class-init.php like this: $this->loader->add_action( 'admin_post_nds_form_response', $plugin_admin, 'the_form_response');

If you were using procedural code you would simply do add_action( 'admin_post_nds_form_response', 'the_form_response');

the_form_response() is where I’ll have full access to the form data via the $_POST or $_GET superglobals. As shown below, I added a breakpoint to the callback in my IDE to be certain that the hook would work as expected.

pausing php script execution
Inspecting form input with XDebug.

Form Validation and Input Sanitization

Before performing any operations, you must validate the nonce and sanitize the user input properly. I made use of the wp_verify_nonce( $nonce_name, $nonce_action ) function to verify the nonce, and sanitize_key() and sanitize_text_field() functions to sanitize the user input available in the $_POST variable. If the nonce verification fails, the user will get an error message as the server response, using the wp_die() WordPress function.

Note: I accessed the form data using the $_POST variable. Had I submitted the form using the get method, I would instead make use of the $_GET or $_REQUEST global variable.

Only when I’m sure that everything is in order, would I perform a WordPress operation like adding the user-meta to the selected user.

To know more about input sanitization, I recommend that you read through the WordPress Codex: Validating Sanitizing and Escaping User Data here.

Submitting the Server Response

After performing the server operations, it’s important to send the server response back to the user. To do this, you will first need to redirect the user back to an admin page or one that provides some feedback. I redirected the user back to the plugin page and used WordPress admin notices to display the server feedback. The server response in my example simply outputs the $_POST variable as a WordPress admin notice.

form post server response
Server response from the form handler.

Progressive Enhancement

At this stage, I have a fully functional form in the admin area of my WordPress plugin. It’s secure and submits properly to my form handler, where the input data is sanitized and finally, the server response is visible. The form will work out of the box in all browsers that have support for HTML5. But there’s a lot I can do to improve the user experience such as adding AJAX support.

This approach of establishing a basic level of user experience that’s available in all browsers, and then adding advanced functionality for browsers that support it is called Progressive Enhancement.

Note: I’ve made the assumption that my users use modern browsers with HTML5 support. However, if the form had to be rendered on an older browser, the built-in HTML5 input validation for required fields would break. Can I Use is a great website that you can use to compare web features that are available across browsers and browser versions.

Form Submissions with AJAX (admin-ajax.php) in WordPress

AJAX in WordPress is handled via the wp-admin/admin-ajax.php file. Here’s an overview of how custom forms can be processed via AJAX in WordPress:

form support with ajax
Form submission with AJAX support in WordPress.

You’ll notice that it’s quite similar to how forms are processed using admin-post.php. When WordPress receives an AJAX request it will create two hooks based on the supplied action:

  • wp_ajax_{$action} for logged in users
  • wp_ajax_nopriv_{$action} for non-logged in users

Where $action is the name of the action that was passed.

Adding AJAX Support to the Plugin Form

The second menu page of the plugin “Ajax Form Submit” loads the form that’s submitted via an AJAX request. It’s added to the menu page in the same manner as discussed earlier, and uses the partials-ajax-form-view.php file to load the form content. If you look at this file, you’ll notice that it’s nearly identical to the earlier form with the only differences being the value of the form id attribute and the title. Now that I can identify one form from the other, I can process just the second form via AJAX using JavaScript.

To add AJAX support, I performed the following steps:

  • Enqueued a JavaScript file to load the jQuery
  • Used jQuery submit event handler to prevent the normal form submission
  • Used jQuery.ajax() to submit the form to admin-ajax.php instead of admin-post.php

Note: If for some reason JavaScript is disabled in the browser, jQuery or AJAX will be unavailable too, but the form will still submit normally. This is because I left the form submission URL as admin-post.php in the form HTML.

Using JavaScript and jQuery to Post the Form

Here’s the JavaScript that I used to submit the form via AJAX.

event.preventDefault(); is what actually prevents the normal form submission.

I gathered the form data using jQuery’s serialize() function but there are many other ways to do this. One of them is using HTML5’s FormData interface. It’s beyond the scope of this article but it’s definitely worth looking at.

var ajax_form_data = $("#nds_add_user_meta_ajax_form").serialize();

I also added additional URL parameters to the serialized data, so I can distinguish between an AJAX and a regular request in the PHP form handler later.

ajax_form_data = ajax_form_data+'&ajaxrequest=true&submit=Submit+Form';

Typically, the X-Requested-With HTTP header is automatically set to XMLHttpRequest by the AJAX library. This can also be used to identify an AJAX request but it’s not always reliable.

The ajax() method of jQuery will submit the request to the server.

To get the form to submit to admin-ajax.php, I used an array params.ajaxurl that was passed in from PHP using wp_localize_script.

Note: The form data in my example includes the action that WordPress will use to generate the hooks for the AJAX request. The following hooks will be triggered by WordPress:

  • wp_ajax_nds_form_response for logged in users
  • wp_ajax_nopriv_nds_form_response for non-logged in users

The JavaScript file is enqueued in the enqueue_scripts() method of class-admin.php as below:

The ajaxurl Global Variable

You can also use a global JavaScript variable ajaxurl instead of passing the URL for admin-ajax.php from PHP. However, the variable is available only when dealing with the admin end and is unavailable when dealing with AJAX on the frontend.

Depending on the response from the server, the AJAX promise callbacks .done() and .fail() will execute accordingly. In my example, for a successful request, I’ve added the response to the empty div container #nds_form_feedback that was part of my form HTML. Finally, the fields are cleared by reseting the form.

The Form Handler for the AJAX Request

I’ve attached the same form handler the_form_response to the AJAX request as well.

And in the form handler, I used $_POST['ajaxrequest'] that was set manually in the JavaScript to distinguish between a normal and AJAX request.

pausing script execution to verify ajax
Validating the AJAX request using a breakpoint.

That’s it. With AJAX, the response is displayed without the page being reloaded or redirected.

If JavaScript was disabled or did not load for some reason, $_POST['ajaxrequest'] would not be valid, and the form would submit normally by skipping the AJAX specific if( isset( $_POST['ajaxrequest'] ) && $_POST['ajaxrequest'] === 'true' ) code block.

You can certainly do a lot more to improve the user experience, and I recommend you read through the jQuery API documentation for AJAX here.

Additional Resources

We’ve covered a lot of ground here. AJAX is a fairly vast topic and is implemented in several ways. Here are some more examples of using AJAX in WordPress:

]]>
https://wpmudev.com/blog/handling-form-submissions/feed/ 11 2022-01-17T13:00:49Z
How to Install XAMPP and WordPress on Windows Localhost https://wpmudev.com/blog/setting-up-xampp/ https://wpmudev.com/blog/setting-up-xampp/#comments Sat, 15 Jan 2022 11:00:00 +0000 http://premium.wpmudev.org/blog/?p=150594 Once you’ve experienced speed and reliability, there’s no going back. Remember the era before high-speed internet, when you had to wait for videos to buffer? Awful times. Three cheers for the modern internet speeds!

If you’re used to developing your sites on a live server, that’s exactly what shifting to a local development environment such as XAMPP would feel like. Blazing fast development and exceptional reliability. You can never go back to the old ways.

In this post, I’ll be showing you how to install XAMPP on your Windows PC and have a WordPress site (including Multisite) running on it in just a few minutes. I’ll also cover some common issues that you may encounter and how to overcome them.

Continue reading, or jump ahead using these links:

If you prefer a video instead, we’ve got you covered!

What is XAMPP?

In a nutshell, XAMPP is a local server that you can install on your laptop/desktop to mimic an actual web server.

It’s a completely free, open source Apache server distribution with MariaDB (formerly MySQL), PHP, and Perl. XAMPP is available for all major operating systems, and is extremely easy to install and use. This explains why it’s the most popular PHP development environment.

Here’s what the alphabets in XAMPP stand for:

  • X — cross-platform (X), as it supports multiple operating systems
  • A — Apache HTTP Server
  • M — MariaDB (formerly MySQL)
  • P — PHP
  • P — PERL

Apart from the core components mentioned above, XAMPP usually comes with other useful tools such as Mercury mail server, phpMyAdmin for database administration, Webalizer for web server log analysis, OpenSSL, Apache Tomcat for running Java code, and FileZilla FTP server.

Why XAMPP?

As a professional WordPress developer, I cannot stress enough how beneficial having a local development environment is. It lets me setup new WordPress installs in a jiffy. And since it’s hosted locally on my computer, there’s no delay in uploading my changes and see them come alive on the browser.

Want to try a new theme? Just copy and paste it into your wp-content/themes directory. And bam! It’s loaded instantly. The same with plugins and changing any settings. No server delay, no upload hassles, no unnecessary waiting times. Everything happens in real time.

It’s like taking your car on a racetrack and pushing it to its limits. The perfect testing environment to go wild without any repercussions (well, almost).

With XAMPP installed on my PC, I can continue working on my site even if I’m at a remote location with no connectivity. Developing locally is also much secure, as your site is offline and away from the prying eyes of hackers (and pesky clients).

Why Use Xampp to Create Local WordPress Sites?

Like all software, WordPress has certain prerequisites to run. The current recommended WordPress requirements are:

  • PHP version 7.4 or greater
  • MySQL version 5.7 or greater OR MariaDB version 10.2 or greater
  • HTTPS support
  • Apache OR Nginx server

XAMPP checks all the boxes listed above. It’s free, reliable, easy to use, and works on all major platforms. You can’t go wrong with it.

Steps to Install XAMPP on Windows

  1. Download XAMPP
  2. Install XAMPP 
  3. Open the XAMPP Control Panel
  4. Start Apache and MySQL Modules

Step 1: Download XAMPP

Start off by downloading the latest version of XAMPP from Apache Friends website. The current up-to-date version of XAMPP is 8.1.2 / PHP 8.1.2.

XAMPP PHP most recent file versions
XAMPP & PHP most recent file versions.

Note: If you’re using Linux or OSX, the installation steps are pretty much the same. Just make sure to download the appropriate version of XAMPP for your OS.

Step 2: Install XAMPP

Once downloaded, run the XAMPP installer file.

The XAMPP Setup Wizard
You might get a UAC warning before installation. Click OK and continue.

Select the components you want to install. If you’re planning to install a WordPress site with XAMPP, you only need Apache, MySQL, PHP, and phpMyAdmin. I’ll check all the components as I’d like to experiment with them later.

Choose the installation directory for XAMPP (default recommended).

Uncheck Learn more about Bitnami option. Bitnami provides all-in-one tools to install popular open source apps on top of XAMPP. This includes add-on modules for installing WordPress too. However, we’ll be installing it manually here.

You may be presented with a Windows Security Alert at the end of the installation. You need to whitelist Apache HTTP Server from your Windows Defender Firewall by clicking the Allow access button. Make sure to check the “Private networks, such as my home or work network” option. This is very important. XAMPP won’t work if you don’t check this and click Allow access.

Complete the setup and run XAMPP Control Panel.

Installation Note 1: Deactivate UAC under Windows Settings

You might be presented with a User Access Control (UAC) warning by Windows. Nothing to worry much. Just make sure that you don’t install XAMPP under your Program Files directory, as UAC can interfere with XAMPP’s writing permissions to this directory. The default installation directory is C:\XAMPP. So, if you don’t change it, you should be good.

If you want to learn how to deactivate UAC (not recommended unless absolutely necessary), Microsoft Windows support is a good place to start.

Installation Note 2: Deactivate Antivirus and/or Firewall Temporarily

Some antivirus or firewall programs can cause issues with your XAMPP installation. If that’s the case, it’s suggested that you deactivate them temporarily until XAMPP is installed successfully.

Read the XAMPP Windows FAQs page for more.

Step 3: Open the XAMPP Control Panel

The XAMPP Control Panel sports a simple user interface that lists all the modules of your local server. It allows you to Start/Stop individual modules, access their Admin area, Config files, and Logs with just a single click. Its bottom section also displays all your actions and errors (if any).

Apart from the options discussed above, the XAMPP Control Panel also features other buttons on its right side:

    • Config: to configure overall XAMPP settings
    • Netstat: display all active TCP connections (and ports) on your computer
    • Shell: starts XAMPP in a custom command line (CMD)
    • Explorer: opens the XAMPP root folder in Windows Explorer
    • Services: shows all Windows services under Microsoft Management Console
  • Help: links to Apache Friends Support Forum
  • Quit: quit XAMPP Control Panel (the server will continue to run in the background)

Step 4: Start Apache and MySQL Modules

Click the Start button beside Apache module. If everything’s set correctly, your Apache server should start successfully under ports 83 and 443.

You can access your Apache server’s dashboard by clicking the Admin button beside it. Alternatively, you can also reach it via http://localhost/dashboard/ URL in your browser.

Then Start the MySQL module. If you’re presented with a Windows Security Alert to whitelist mysqld.exe, click Allow access. Like before, make sure that you’ve ticked the “Private networks,…” option.

Don’t forget to tick the “Private networks” option.

You can access your phpMyAdmin dashboard by clicking the Admin button beside MySQL module. Or you can simply go to http://localhost/phpmyadmin/ in your browser. Here, you can manage the MariaDB (or MySQL) databases of your web projects.

The phpMyAdmin Dashboard

This concludes the setup of XAMPP as your local development environment. It’s now ready to host any PHP-based software (e.g. WordPress).

Testing Your XAMPP Installation

The best way to check whether your local server has been installed and configured correctly is to create a PHP test page, place it in XAMPP’s localhost folder, and then try accessing it via your browser.

Let’s do that now. Create a new folder called test in your C:\xampp\htdocs\ directory. This directory can also be accessed easily by clicking the Explorer button in XAMPP Control Panel and then going to htdocs folder.

Create a file called test.php with the code below and place it in C:\xampp\htdocs\test folder.

Try visiting http://localhost/test/test.php in your browser. If it displays the words “Hello World! Welcome to WPMU DEV”, then XAMPP is successfully installed and configured on your system.

Installing WordPress Locally with XAMPP

Step 1: Create a New MySQL Database for Your WordPress Installation

Before we install WordPress, we need a database.

In your XAMPP Control Panel, click the Admin button in the MySQL section. A new browser window will automatically open with the phpMyAdmin dashboard interface. Click on Databases near the top-left.

You’ll now be prompted to create a new database. I’ve named mine wpmudev.

Once you’ve entered a name, click Create and close the window.

Step 2: Download and Install WordPress

Download the latest version of WordPress.

WordPress download
WordPress download.

Unzip WordPress in the right folder under XAMPP. In my case, it’s C:/xampp/htdocs. Rename it to whatever you like, but it’s recommended to give this folder the name of your site. I’m going to call this installation of WordPress wptest.

Now, go into your site’s WP folder, find the wp-config-sample.php file, and rename it wp-config.php.

Open the file and scroll down until you see the following lines:

These lines of code define the login details for your database. Update them as per the instructions below:

  • Replace “database_name_here” with the name of your database, which in my case is wpmudev.
  • Replace “username_here” with “root” and edit “password_here” field to be empty.
  • Save the file and close it

We can continue with our WordPress installation now. Open your browser and go to http://localhost/wptest/.

You should see the WordPress installation’s language selection screen load.

Once you’ve chosen your language, continue onto the next screen. Enter your site title, admin username, and password details. Click Install WordPress.

Congrats, you’ve successfully installed WordPress on your local server.

Setting Up WordPress Multisite Locally with XAMPP

Step 1: Enable WP Multisite in your wp-config.php File

Open your wp-config.php file and add the following line just above the line that says /* That’s all, stop editing! Happy publishing. */.

define('WP_ALLOW_MULTISITE', true)

This will activate the Multisite installation mode on your WordPress site.

Step 2: Setup Your Multisite Network

Go to your WordPress dashboard, and then to Tools > Network Setup.

Enter a name for your multisite network and your network admin email address. Then click Install.

WordPress will now prompt you to edit your wp-config.php and .htaccess files.

Follow the instructions given.

Step 3: Follow WordPress’ Onscreen Instructions

Open your wp-config.php again and add the code given by WordPress underneath your previous edit.

Next, open .htaccess file and replace all its code with the one given by WordPress (Note: you’ll have to replace the contents completely here, not just add/edit).

If you can’t find the .htaccess file, make sure to enable display hidden files settings on your computer. If you still can’t find it, then create one in the same directory as your wp-config.php file.

Multisite should now be successfully activated on your WordPress installation.

You’ll have to log in again. And when you do, you’ll be able to access individual sites in your multisite network from your dashboard.

You can also create a new network site from here by clicking the Add New button.

Adding a New Network Site

Troubleshooting Common Issues with XAMPP & WordPress

While my XAMPP and WordPress installation went without a hitch, not everyone is so lucky. XAMPP can throw a curveball at you at any stage of its and WordPress’ installation. Here are some common issues associated with XAMPP (click to go to its solution):

XAMPPing Up

XAMPP allows you to set up a local server environment on your Windows machine easily. The best thing about it is that it’s completely free and open source. Once installed, you’ll forget that it’s even there. You can even install XAMPP on a USB drive along with WordPress.

With XAMPP, you can develop and test WordPress sites swiftly on your system, rather than doing it the hard way on a live site. You can try different themes and plugins, test their various features, and experiment with many other aspects of your site without breaking a sweat.

What’s more, you can also install as many instances of WordPress as you like (including Multisite). Who knew the saying “think global, act local” holds true for web development too!

]]>
https://wpmudev.com/blog/setting-up-xampp/feed/ 142 2022-01-15T11:00:00Z
Loading WordPress Posts Dynamically With AJAX https://wpmudev.com/blog/load-posts-ajax/ https://wpmudev.com/blog/load-posts-ajax/#comments Sat, 15 Jan 2022 08:00:00 +0000 http://premium.wpmudev.org/blog/?p=136223 AJAX (Asynchronous JavaScript and XML) is a way to have a “conversation” with the server and display the results without reloading the page.

This technique allows us to refresh “Like” counters, add items to a shopping cart, create dynamic forms and much more – all without reloading the page.

In this post, I’ll show you how to load posts in place with AJAX using the Twenty Fifteen default theme as our base.

We’ll look at why AJAX is used and, starting with a simple example, building AJAX loading functionality into Twenty Fifteen.

Note: If you run into any issues trying to set up AJAX on your site, we can help! Our support team is available 24/7 to help you with any WordPress issue (not just questions about our own plugins!), so whether you’re having problems with AJAX or want some advice on how to do CSS tweaks, get in touch! 

Why Use AJAX?

When WordPress loads the first page of posts on a WordPress site, it requests them from the database and uses a loop to display them using the markup we’ve added. Aside from this, navigation menus, widgets, graphics and other media, javascript files, stylesheets and a bunch of other things are loaded.

Network requests.
Note that 72 requests are made on each page load.

As you can see in the image above (taken from Chrome Developer Tools), a fair number of assets are loaded. There is room for optimization here and some assets like scripts will be cached, but even then it is a lot.

When page two of our posts is loaded it all happens again. WordPress retrieves the posts and displays them using our markup. It also loads all the outlying elements of the page all over again. In many cases (but not all) this is a waste of bandwidth and detrimental to user experience. After all, no one likes waiting around for pages to load.

Getting Started: Creating a Child Theme

Before we modify Twenty Fifteen we should create a child theme. This ensures we can continue updating the theme without losing our changes. You can read all about how to do in in out guide How to Create a WordPress Child Theme.

Hello AJAX!

Let’s begin with a simple example that demonstrates how AJAX Works. We’ll target the links inside the pagination strip at the bottom of the page so that when you click on a page number it will dynamically load that page using AJAX. When a pagination link is clicked we will send a request to the server and alert the result.

Pagination
We’ll be targeting the number links inside the pagination section.

Enqueuing Our Javascript

Our first port of call is creating the JavaScript file and enqueueing it via our theme’s functions.php file.

I created a js folder and a ajax-pagination.js file in it. Once you have done the same, open your functions file and add the script to the already existing theme_enqueue_assets() function:

If you’re confused about enqueuing read our article on adding scripts and styles to WordPress the right way. In a nutshell, we’ve told WordPress what we’d like to call our script (parameter one), where it is located (parameter two), what the pre-requisites are (parameter three), the version number (parameter four) and that we’d like to load it in the footer (parameter five).

Note that when enqueueing the stylesheet I used get_template_directory_uri(). This function always points to the directory of the parent theme. When enqueueing our script I used get_stylesheet_directory_uri(). This points to the child theme’s directory if used within a child theme.

Since we’re loading the script in the footer you can paste alert( 'Script Is Enqueued' ) into ajax-pagination.js and reload the page to check if it works. If it does, the text should be alerted properly.

Creating an Event

The next task is to create an event which will trigger an AJAX call. In our case the event is the clicking of a specific link. To target the link we’ll need to find out a bit about the element classes and IDs around it.

Pagination Source
The source code for the pagination from Chrome Dev Tools.

In case you’re wondering how I got this to show up, I pressed Shift + Command + C on my Mac (Shift + Control + C on Windows), hovered over the element I wanted to inspect and clicked it.

This tells me that our pagination links have the class page-numbers, the next link also has the class of next and these are all contained in a nav element with the class of nav-links. Not shown here is the previous link, which has the class of prev in addition to the regular page-numbers class.

For the time being, let’s not worry about all that, let’s just target any link within the pagination container. We can create a simple alert like this:

Note that everything is wrapped in an anonymous function. I recommend you do the same. Take a look at this thread on why this is helpful. I’ve created a click event, prevented the default functionality from firing (i.e. loading the page) and I’ve alerted some text.

Creating an AJAX Call

Instead of working with client side data (alerting a preset text) we should grab some dynamic data from the server side. We’ll need to do a tiny amount of prepwork. Here’s why: We need to give the AJAX call a URL to work with. Our Javascript file has no knowledge of our environment, so we can’t use something like get_stylesheet_directory_uri() in there. We can, however, use a localization technique to pass variables to our JavaScript. Let’s do that now in our functions file:

By adding this code inside the my_enqueue_assets() function we will have defined the ajaxpagination object (parameter 2). The object will receive its members according to the array supplied as the third parameter in the wp_localize_script() function. In other words, once we’ve added this code we should be able to use ajaxpagination.ajaxurl to define the URL to the admin-ajax.php which we use to handle AJAX calls.

The reason this works is that the localization function outputs the definition of this object before our JavaScript is loaded. It looks something like this:

Getting back to our JavaScript file, we now have everything we need to build an AJAX call. Here’s how:

As you can see the $.ajax() function is what we’re using here. There are special functions for post and get methods but I prefer using this function because of its flexibility. You can read about all the parameters in the jQuery Documentation.

Using the url parameter we pass the URL of the script we want to send data to. This should be the admin-ajax.php file which can be found in the wp-admin directory. We defined this above via the wp_localize_script() function.

The type is set to post. We could also use get, our query is not too sensitive but I prefer to post data unless the user needs access to the parameters.

The data parameter is an object which contains the data you want to pass. In our case I will be able to access a $_POST['action'] variable, the value of which would be ajax_pagination. You can pass as many as your application requires of course.

AJAX Call Alert
0 is returned if no server-side code is written.

Finally, the success parameter is a function which alerts the result of our AJAX call. We’ll make this a bit fancier below, for now this is sufficient for testing. If you try clicking on a link now it actually works but won’t be very useful since we haven’t defined the server side code. In fact, what you should see alerted is 0.

So why does this happen? When I said “we haven’t defined server side code,” I wasn’t entirely truthful. We haven’t, but WordPress has. There is some content in the admin-ajax.php file we are using. If you take a look at the source code of that file you should see that the script uses die( '0' ) in a couple of cases.

If we don’t supply an action the admin-ajax.php script dies and returns 0. If we do supply an action but we don’t hook into the required WordPress hooks nothing happens and at the very end of the file we die again, returning 0. In conclusion we are already communicating with the server.

Communicating With WordPress

To get a meaningful answer from WordPress we need to define some WordPress actions. This is done using a set pattern. Let’s dive in by continuing our example in the functions file of our theme:

I’ve hooked a function to two hooks. Hooks that take on the wp_ajax_[action_name] format are only executed for logged in users. Hooks that take on the wp_ajax_norpiv_[action_name] format are only executed for non-logged in users. The great benefit of this is that you can very easily separate functionality.

The action names I mentioned above refer to the action defined in our AJAX call in Javascript (action: 'ajax_pagination') – they must match. The function name can be anything you like, I used my_ajax_pagination for clarity.

The function itself can contain anything you’d like. You can log out users, grab their data, publish a post and so on. Whatever you want to return to Javascript you must echo. In the example above I’ve echoed the title of the blog, pulled in dynamically via the get_bloginfo() function.

The final step is to use die(). If we don’t define this, the die function defined in admin-ajax.php at the very end of the file will kick in and you will end up echoing 0 in addition to whatever else you are echoing. If you try out the code above you should now see the title of your website returned.

Overview

That concludes our basic example! Before we move on to pulling in posts via AJAX, let’s quickly recap the steps necessary to perform an AJAX action:

  • Enqueue a Javascript file if you don’t already have one
  • Use wp_localize_script() to pass the URL of your admin-ajax.php file
  • Create the AJAX call in Javascript
  • Hook a function using the appropriate hook name
  • Code the function which may return data back to Javascript

Loading Posts With AJAX

Now for the juicy stuff! I started this project by writing the JavaScript code for it. Without further ado, here is the basic version. We’ll expand on it with some tweaked user experience soon.

This is much the same as our basic example. The first thing you’ll notice is that I’ve added a way to detect which page the user wants to request. Each link has a span element in it which is hidden (it is there for screen readers). I make a clone of the element to make sure I don’t modify the original, remove the span and parse the remainder as an integer. This gives us the page number we need.

I will also need to know the query parameters used. On the main page this is pretty simple, it’s just the paged parameter since we’re working with the default query. If we start off on an archive page (like a category archive) we’ll need to know the category name as well.

We’ll pass the query variables using the localization method we learned earlier. For now we’ll use ajaxpagination.query_vars even though this is not yet defined. Finally, on success we remove all article elements from the main container, we remove the pagination element and append the return value of our AJAX call to the main container.

This return value will contain the posts and the new navigation element. Note that I’ve changed the name of the parameter from response to html because it makes a bit more sense. To finish up we use the localization array to pass the original query parameters.

The following function should be placed in our my_enqueue_assets() function replacing the localization we had earlier:

All we need to do now is flesh out the my_ajax_pagination() function. Whatever this function echoes will replace the content on our page. Here’s the final code with an explanation below:

Using our passed parameters we build a custom query. This involves basically taking the query variables we passed and making sure that the page number we passed overwrites the paged parameter. We then use our final $query_vars array to create a new query.

We need to make the $GLOBALS['wp_query'] variable equal to our new posts object. The reason we need to do this is that the the_posts_pagination() function uses this global variable.

Next, notice that I’ve added a function to the editor_max_image_size filter and a few rows down I remove it. This was something unexpected that came up. I actually created a WordPress Trac Ticket. We may see some progress on it! Here’s the issue:

When images are loaded in the post they all look just fine. However, if you complete this tutorial without these filters your images will be narrower, only 660px wide instead of the necessary 825px. The reason for this is that the function that loads the images eventually calls a function named image_constrain_size_for_editor(). This function makes sure that images in the post editor aren’t too wide. To determine weather this size reduction should take place it uses the is_admin() function. Since our code runs through admin-ajax.php which technically is in the admin, WordPress scales our images down, mistakenly thinking we are using them in the editor.

Luckily we can use the editor_max_image_size filter to determine the maximum size for the editor. Since we want to leave everything as is, except for during our AJAX call we add the filter using our custom values (array( 825, 510 )) and then immediately remove it just to make sure it doesn’t cause trouble anywhere else.

The next step is to use our query to list our posts. I copied a lot from the index.php file in the parent theme. if there are no posts we use the template which is meant to handle that, otherwise we loop through the posts and use the post display template. Finally we use the same pagination format we see in the index file.

A Note About AJAX Calls

It’s important to remember that AJAX calls are always considered to originate from the admin. What this means is that draft, scheduled and private posts may be returned with this call. If you don’t want this to happen, you’ll need to control the behaviour with appropriate parameters such as post_status.

Better User Experience

With AJAX solutions like this, it is extremely important to focus on user experience. I’m working in a local environment so everything loads really quickly, but on a production server images and other assets may take more time to load.

Due to this you should at least add a loader or loading text and disable further clicks on the navigation elements. We will take care of these by making the posts and the navigation disappear right after the user clicks and displaying the text “loading new posts.” When the success event fires we remove the loading text and display the posts. Here’s our updated AJAX call:

We now have a separate beforeSend and success function. The former is performed as soon as you click the link, before the AJAX call is sent to the server. The later is performed once we receive data back from the server.

Before the call is sent we remove the articles and the navigation. This makes sure users can’t keep clicking on navigation links while they’re waiting for things to load. Next we scroll to the top of the document. Then, we append a loading notification to make it clear to users what’s going on. I’ve used the same markup as Twenty Fifteen uses on post-not-found pages. In the success function we remove the loader and load our content, all done!

AJAX Pitfalls

AJAX is extremely powerful; apart from loading posts you can perform all sorts of actions via AJAX calls. There are quite a number of dangers and things to look out for while using it, here are a few:

Safety can be a major concern. If you want to delete a post via AJAX you need to make sure the user has the intent and the permission (using nonces), for example. When using regular methods WordPress has built-in protections in some cases but with AJAX you usually have to think of this on your own.

Graceful degradation is another facet of AJAX, although something that is becoming less important. Basically: no JavaScript, no AJAX. If you rely on AJAX heavily, users who have it disabled will not be able to use our application. Javascript has become so ubiquitous that this is almost irrelevant, but may come up in some situations. In this case you need to make sure that clicking on the actual link will work as well.

User experience is very frequently overlooked. AJAX functionality is indeed cool, but a reliably working website is cooler. Users are used to pages loading when they click links. You need to make everything very transparent, users should know what is going on and why. You should use AJAX to enhance your work, not to bring as much bling as you can to the table.

Conclusion

As you can see, implementing AJAX requires a bit of preparation and practice but once it’s second nature you’ll find that it comes easily. It probably took you a while to read through this and it will take even more time to do it for the first time, but I coded the whole example in about 15 minutes.

AJAX is one of those techniques which can be difficult because it encompasses almost all programming languages used in a framework like WordPress. Things are spiced up further by having to adhere to conventions like hooks and localization.

Practice makes perfect. I guarantee you’ll fall in love AJAX if you start to use it.

]]>
https://wpmudev.com/blog/load-posts-ajax/feed/ 39 2022-01-15T08:00:00Z
Awesome Website Headers For Your Inspiration https://wpmudev.com/blog/website-headers-inspiration/ https://wpmudev.com/blog/website-headers-inspiration/#comments Mon, 10 Jan 2022 13:00:03 +0000 https://premium.wpmudev.org/blog/?p=167154 In the past, a “header” in web design referred to the ever-present strip at the top of websites that contained the logo, navigation bar, and maybe some contact details and search bar. Nowadays, a “header” refers more often to the entire space above the fold on the home page.

Unless someone’s found your site through a blog post shared on social media or from a referral on another site, chances are good they will enter it through the home page. And the first thing they’ll see is that prime real estate up top laid bare.

I’ve written before about how visitors respond better to the predictable placement of certain elements on your website (like the logo and CTA). By designing a website with the goal of meeting their expectations and enhancing their comfort by making the experience somewhat more predictable, you can effectively improve click-through and conversion rates.

Now think about that header space on the home page.

Quickbooks header
What exactly is a “header” these days?

Most people have come to rely on home pages to give them a bird’s-eye view of what a company or website is about, which means you can’t afford to waste this opportunity to deliver on that expectation.

Of course, your home page header design can be unique to your brand, but the elements found within it really shouldn’t be. Visitors expect scrolling won’t be necessary to find out what a site will do for them. In essence, your header should be a 10-second story that proves to your visitors what value the site will be to them.

So, what will you do with this space to captivate your visitors’ interest?

Let’s talk about some of the trends in header design, what you can do to make use of this highly visible real estate, and take a look at some interesting examples of headers along the way.

Note: Not all of the example sites listed below use WordPress but they can be done using WordPress.

Header Web Designs for your inspiration

It’s not like your visitors are unaware of their ability to scroll down a page or click-through navigation to learn more about the brand behind a site. But why should they have to do that?

There is enough room in the header to provide a succinct message that tells them everything they need to know. And if 50 words or less isn’t enough, the background image or design will communicate the rest of the story.

Above all else, the home page header can make or break your visitors’ first impressions, which is why it’s so important to nail this section.

If you’re struggling to find a way to kick off your site with a bang, maybe you’ll find some inspiration in the following header designs.

1. Oversized Hero Image

Cleverbird Creative website.
Some headers, like Cleverbird Creative’s, are huge.

Thanks to the modular style of designing sites to be responsive, most designs are now broken up into distinct blocks and sections. This design style happens to lend itself well to these full-width hero images that populate so many websites.

Take the Cleverbird Creative website, for example. It makes use of a singular and striking image overlaid with simple text to welcome visitors. There’s no mistake what they’re going for here: simplified beauty. Plus, having Wonder Woman doesn’t hurt.

2. Sliding Images

Scrolling image example.
Mmm… ice cream…

I think there was a time, not too far in the past when many of us were questioning the slider as a viable design element. However, many designers have done a great job making use of it in headers. There are sliding images that automatically scroll from one beautiful high-resolution image to the next and there are those like Pierre’s that beg visitors to take control of that experience themselves.

3. Transformative Parallax Imagery

The Anakin Design Studio website.

Parallax has been a feature of modern web design for some time. Although considered “hot” some years ago, using parallax effects is still popular and the header has proven to be the perfect place to apply this sort of visual “illusion” to web designs. However, what you’ll see most recently is designers giving their parallax scroll a transformative edge, probably to surprise visitors with the unexpected result of the scroll. The Anakin Design Studio has done just that with its header.

4. Video Backgrounds

Example of a video background.
The Brave People website does a great job incorporating videos.

The video background is another one of those recent trends that really works best when applied to the home page header. This one from Brave People does a great job of setting the tone of their website, showing off various clips.

5. Hidden Navigation

The Canals header example.
Canals header is super modern and the navigation is hard to spot.

Although it could be argued that the hamburger menu belongs on websites viewed on mobile devices (as originally intended), there is something to be said about what that sort of navigational minimalism does for the header. The Canals website is a nice example of this. By tucking the navigation away, your immediate focus is drawn to the exciting visuals.

6. Brand Mascot

Mascot header example.
As Tony the Tiger would say about mascot headers: “They’rrrrrrre great!”

If the header is the place to introduce visitors to your site, what better way to kick it off than by introducing them to the “characters” they’re going to meet along the way? If your site uses a brand mascot—as the Kellogg’s Frosted Flakes site does—this is the time and place to show them off.

7. Eye-Catching Typography

Slack website example.
Strong typography can really make your content shine.

There’s a lot that can be done to give your site’s typography a facelift. That said, sometimes it’s not about choosing the fanciest cursive font to throw in people’s faces. If you look at the Slack example above, you’ll see that it’s all about the size of the font. There’s nothing really special about the typography they’ve chosen, but it’s so clean and clear. That paired with the size of the main message is what makes it so eye-catching.

8. Content First

Example of Glamour's homepage.
Glamour’s home page is content-first, among other things.

For websites with a primary focus on delivering droves of content to visitors (think of any major news site or blog), a content-first strategy for the header will make the most sense. There’s really no point in mincing words here. People have come to your site to read your content, they don’t need to be bogged down by additional reading on the home page, so you can get right to it as Glamour does.

9. Products First

Example of Apple's website.
Meanwhile, Apple’s focus is its latest big product.

Along those same lines, e-commerce sites don’t need to bother using the header to write a catchy headline or provide a video explainer about the company. Visitors know what they’ve come to the site for, so you can get right into it. However, unlike content providers, product retailers can use this prime real estate to show off their top-selling products or newest releases to entice visitors onwards as Apple does.

10. CTA Front-and-Center

The Everywhereist directs visitors to click its bold CTA.

There may come a time when your site has something truly special to show off to visitors, something you want them to download or buy. Now, even though that might not be the main attraction of your site, you can use the header either temporarily or permanently to highlight this special call-to-action as the Everywhereist blogger does with her book.

11. Vibrant Colors and Textures

Example of Stripe's website.
Ooh… shiny…

One of the nicest things to come out of Google Material Design is our willingness to use more vibrant colors, layers, and gradients in web design. They no longer have to be relegated to call-to-action buttons, they can be used for entire blocks on the website, as Stripe does with their colorful and texturized header.

12. Animation

Disney's website.
Disney’s website often features animations of their latest project.

There’s absolutely nothing wrong with having a static home page header design, especially if you want the focus to be drawn to a CTA or video. Please keep it simple so there are no distractions keeping visitors from taking the action you intended them.

But for websites that want an interesting way to share their message with readers, try animation. For example, Disney uses a small animation to share a number of messages within the same space, which keeps it from looking cluttered or overcrowded with information.

13. Geometric Designs

Perspective's website.
Perspective API’s stripped-back header.

Geometric web design happens to be really big right now as it lends itself well to the logical and clean lines needed for responsive design. So it’s no surprise that we’re seeing more websites, like the one for Perspective API, integrate geometric elements into the header’s design. Others, like Stripe and WPMU DEV, use diagonal lines to create a unique and unexpected visual landscape for visitors.

14. Experimental

Teamgeek’s header is weird and fun.

Finally, we come to experimental header designs. The key to these usually isn’t that the header is outlandishly strange and unusual. That would be too distracting for visitors. Instead, your focus should be on creating some unexpected effect caused by the simple movement across the header.

Take the Teamgeek design, for example. You can see that there’s something “off” about the logo and message within the center of the page, but it’s not until you engage with it that you realize there’s a special twist built-in.

Wrapping Up

As you can see, there are various ways you can design a header for a WordPress site. If you look closely at the examples above, though, you’ll notice that the designers were very strategic about what style of header they used and which elements were included within it. When it comes time to design a header for your next website project, consider whether you’ll need the following:

  • Logo
  • Traditional vs. hidden
  • Hero header section vs. getting straight to the content
  • Tagline or mission statement
  • Contact information
  • Social media links
  • Search bar
  • Multilingual toggle
  • Shopping cart
  • Brand mascot
  • Stock photography vs. actual photography of the company, people, or product
  • Static image vs. sliding images vs. background video
  • Embedded promo video
  • Call-to-action button
  • Contact form
  • Hello bar

You may find other items that belong in this top header section of your home page, too. It really just boils down to what makes the most sense for your site.

In other words, which elements will tell your brand’s story, educate and engage your audience straight out the gate, and inspire enough trust to propel them forward through your site?

Editor’s Note: This post has been updated for accuracy and relevancy. [Originally Published: August 2017 / Revised: August 2021]

]]>
https://wpmudev.com/blog/website-headers-inspiration/feed/ 17 2022-01-10T13:00:03Z
How To Properly Add jQuery Scripts To WordPress https://wpmudev.com/blog/adding-jquery-scripts-wordpress/ https://wpmudev.com/blog/adding-jquery-scripts-wordpress/#comments Mon, 03 Jan 2022 11:00:29 +0000 http://premium.wpmudev.org/blog/?p=153734 WordPress has been in our lives for over 16 years, yet the method of adding scripts to themes and plugins still remains a mystery for many developers. In this article we finally put the confusion to rest.

Since it’s one of the most commonly used Javascript libraries, today we’re discussing how to add simple jQuery scripts to your WordPress themes or plugins.

But first…

About jQuery’s Compatibility Mode

Before we start attaching scripts to WordPress, it’s important to understand jQuery’s compatibility mode.

As you’re probably aware, WordPress comes pre-loaded with jQuery, which you can use with your code.

WordPress’ jQuery also has a “compatibility mode,” which is a mechanism for avoiding conflicts with other language libraries.

Part of this defense mechanism means you cannot use the $ sign directly as you might in other projects.

Instead, when writing jQuery for WordPress you need to use jQuery.

Check out the code below for an example:

The problem is, writing jQuery a gazillion times takes longer, makes it harder to read, and can bloat your script.

The good news?

With a few modifications you can go back to using our lovely little dollar sign once again.

BTW, if you’re new to jQuery, the $ sign is just an alias to jQuery(), then an alias to a function.

The basic structure looks like this: $(selector).action(). The dollar sign defines jQuery… the “(selector)” queries or finds HTML elements… and finally the “jQuery action()” is the action to be performed on the elements.

Back to how we can get around our compatibility issue… here are a couple of viable options:

1.Enter jQuery Stealth Mode

The first way to get around compatibility mode is to get stealthy with your code.

For example, if you’re loading your script in the footer, you can wrap your code in an anonymous function, which will map jQuery to $.

Like in the example below:

If you want to add your script in the header (which you should avoid if possible, more on that below) you can wrap everything in a document-ready function, passing $ along the way.

2.Enter “No Conflict” Mode

Another simple way to avoid spelling out jQuery is to enter “no conflict” mode and use a different shortcut.

In this case: $j instead of the default $.

All you have to do is declare this at the top of your script:var $j = jQuery.noConflict();

Alright, now you know more about writing valid jQuery code for WordPress, let’s add it to our website.

Steps To Add jQuery Scripts To WordPress

  1. Add jQuery scripts to WordPress via enqueueing
  2. Add Scripts to WordPress Admin
  3. De-Register WordPress’jQuery
  4. Shouldn’t You Register Scripts Before Enqueuing?
  5. Add jQuery To WordPress Using Plugins

One of the simplest ways to add jQuery scripts to WordPress is via a process called “enqueueing.”

For a regular HTML website, we would use the <link> element to add scripts. WordPress ends up doing the same thing, but we’ll use special WP functions to achieve it.

This way, it handles all our dependencies for us (thanks WP!).

If you’re working on a theme, you can use the wp_enqueue_script() function within your functions.php file.

Here’s what it looks like:

This function takes five arguments:

  1. $handle – a unique handle you can use to refer to the script.
  2. $src – the location of the script file.
  3. $deps – specifies an array of dependencies.
  4. $ver – the version number of your script.
  5. $in_footer – lets WordPress know where to put the script.

*Something to note about $in_footer is that by default, scripts will be loaded in the header.

This is bad practice and can drastically slow down your site. Therefore, if you want to place your script in the footer, make sure this parameter is set to true.

Adding Scripts To The WordPress Admin

You can also add scripts to the admin. The functions used are exactly the same, you just need to use a different hook.

For example:

Instead of hooking into wp_enqueue_scripts we need to use admin_enqueue_scripts.

That’s it!

Really.

How To De-Register WordPress’ jQuery

But what if you want to use a version of jQuery different to the one WordPress pre-loads?

You could enqueue it… but that leaves two versions of JQ on the page.

To avoid this we have to de-register WP’s version.

Here’s what this looks like:

It’s as simple as using the wp_deregister_script() to de-register WP’s jQuery, and then including the jQuery script you want to add.

In the example above we used Google-hosted jQuery library, but you’ll obviously replace it with the URL of your own script.

Shouldn’t You Register Scripts Before Enqueuing?

If you want to load your scripts when needed instead of directly loading them in your pages – you can register the script earlier on.

For example, on wp_loaded:

Once you’ve done this you can then enqueue the scripts when you need them:

Just remember to use the same names to avoid colliding with other scripts.

Using Conditional Tags

Use conditional tags to only load your scripts when necessary.

This is used more often in admin, where you’d want to use a script on a specific page only (not the whole admin). This also saves bandwidth and processing time – which means faster loading times for your website.

Take a look at the admin enqueue scripts documentation in the WordPress Codex for more information.

Add jQuery To WordPress Using Plugins

The WP plugin directory also has plenty of great plugins you can use to insert scripts to your WordPress posts, pages, or themes.

Some well known JavaScript / jQuery plugin examples include: Advanced Custom Fields, Simple Custom CSS and JS, Scripts n Styles, and Asset CleanUp.

Script Your Own jQuery Story

Gaining a better understanding of jQuery is only going to make the work you do more impactful. Whether it’s for your own website, or client projects.

jQuery is well known for its simplicity, and as you’ve (hopefully) learned in this article, adding simple jQuery scripts to WordPress is easy as pie once you know how.

Yes, there is a little bit of an overhead compared to using vanilla HTML, but there’s also the added benefit of dependency management and clarity.

Not only this, by employing little tricks like bypassing jQuery’s WP default compatibility, you’re going to save yourself a lot of time, effort, and bloated code.

]]>
https://wpmudev.com/blog/adding-jquery-scripts-wordpress/feed/ 21 2022-01-03T11:00:29Z