Kinsta® https://kinsta.com/ Fast, secure, premium hosting solutions Wed, 02 Oct 2024 18:12:31 +0000 en-US hourly 1 https://wordpress.org/?v=6.1.7 https://kinsta.com/wp-content/uploads/2024/09/cropped-Kinsta-black-favicon-1-32x32.png Kinsta® https://kinsta.com/ 32 32 What to ask your web host about security: A checklist for business owners https://kinsta.com/blog/website-security-checklist/ https://kinsta.com/blog/website-security-checklist/#respond Thu, 03 Oct 2024 14:00:18 +0000 https://kinsta.com/?p=185197&preview=true&preview_id=185197 Every day, countless businesses are taking their operations online to attract new customers and scale globally. One of the quickest ways to get a website up ...

The post What to ask your web host about security: A checklist for business owners appeared first on Kinsta®.

]]>
Every day, countless businesses are taking their operations online to attract new customers and scale globally. One of the quickest ways to get a website up and running is through WordPress, which powers over 43% of all sites on the internet.

But with this popularity comes a downside. Bots and hackers are always on the lookout, trying to exploit any vulnerabilities in WordPress sites. These vulnerabilities often arise from installing compromised plugins or themes or using poor hosting that can’t detect or prevent the most common attacks, like Distributed Denial of Service (DDoS) or brute force attempts.

Many business owners fall into the trap of choosing cheap hosting, only to later spend a fortune fending off attacks — attacks that often stem from the inadequate security of their hosting provider.

This is why, as a business, you shouldn’t be swayed by low costs when selecting a host. The focus should be on quality, especially in terms of security. You must dig deeper and ask the right questions or seek detailed information about your host’s security measures before choosing. It’s not enough for a host to promise security. You need to understand how that security is implemented.

That’s where this guide comes in. We’ve created a comprehensive checklist of essential questions you should ask your web host about security before making your decision.

1. Data encryption

Data encryption is critical for safeguarding the information exchanged between your website and its users. Whether it’s customer details, payment information, or confidential business data, ensuring this information is encrypted is non-negotiable.

What to ask:

  • Does the hosting provider offer SSL/TLS certificates, and are they included in the hosting package?
  • What level of encryption is used for data in transit and at rest?
  • How does the host ensure the security of sensitive information (e.g., customer data, financial transactions)?

Why it matters:

SSL/TLS certificates are essential for encrypting data transmitted between your website and its users. They ensure that sensitive information — like credit card numbers or personal details — cannot be intercepted by malicious actors. Without SSL/TLS encryption, your site is vulnerable to man-in-the-middle attacks, where hackers can intercept and manipulate the data flowing to and from your site.

But encryption shouldn’t stop at data in transit. It’s equally important to ensure that your data is encrypted at rest, meaning it’s securely stored on the server, making it inaccessible to unauthorized users even if they gain access to the physical server or the data center.

When choosing a web host, it’s crucial to confirm that they offer SSL/TLS certificates and use strong encryption standards, such as 256-bit Advanced Encryption Standard (AES), to protect your data in transit and at rest.

Ask about their policies and practices for encrypting sensitive information and ensuring your data remains secure, even in worst-case scenarios. Understanding these encryption measures will give you peace of mind, knowing your business and customer data are protected.

How Kinsta handles data encryption

At Kinsta, we protect your data through robust encryption practices, both in transit and at rest.

For example, all verified domains on Kinsta (localhost domains, temporary domains, and custom domains) benefit from our integration with Cloudflare, which includes free SSL certificates with TLS 1.2 and TLS 1.3 enabled — standards that provide strong encryption and are widely supported by all major browsers. This automatic SSL setup means you don’t have to worry about manually configuring your site’s security unless you want to use a custom SSL certificate.

In addition to securing data in transit, Kinsta leverages the Google Cloud Platform’s (GCP) state-of-the-art security measures to protect your data at rest. This means all data stored on Kinsta’s servers is encrypted using 256-bit AES encryption, which protects the data if someone were to gain physical access to the disks in the data center. The encryption keys are regularly rotated and protected with additional layers of encryption, adding further security.

However, it’s important to note that while the disks are encrypted, an attacker who gains access to your website through compromised credentials (like SSH access) or a vulnerability in your site can read unencrypted copies of the files. This makes it crucial to maintain strong security practices at the site level, such as using strong passwords, enabling two-factor authentication, and regularly updating software.

Our commitment to data encryption extends beyond technical measures. Over the years, we have worked hard to become SOC 2 compliant and recently achieved ISO 27001, 27017, and 27018 certifications. See more information in this article’s security audits and compliance section.

2. Firewall and DDoS protection

Your website’s security relies heavily on the strength of its firewall, which serves as the first line of defense against numerous cyber threats, including DDoS attacks.

A robust firewall filters out malicious traffic, prevents unauthorized access, and ensures your site remains available during attempted disruptions. Understanding how your hosting provider implements these protections is crucial for maintaining your site’s security and performance.

What to ask:

  • Does your hosting service include a web application firewall (WAF) as part of the package?
  • How does your firewall protect against DDoS attacks and other common threats?

Why it matters:

A Web Application Firewall (WAF) protects your site from various threats, including SQL injections, cross-site scripting (XSS), and DDoS attacks. These are the most common and potentially damaging attacks threatening your website.

A well-managed WAF can block these threats before they reach your site, minimizing the risk of a security breach and ensuring your site remains accessible.

DDoS attacks, in particular, aim to overwhelm your site with a massive influx of traffic, rendering it slow or completely unavailable to legitimate users. The impact can be devastating, leading to lost revenue, damaged reputation, and frustrated customers.

A strong firewall not only filters out this malicious traffic but also plays a critical role in defending your site against DDoS attacks, ensuring that your site remains operational even during an attack.

Effective firewall and DDoS protection involves more than just setting up basic defenses. It requires continuous monitoring, automated threat detection, and the ability to absorb and mitigate large-scale attacks.

How Kinsta handles firewall and DDoS protection

At Kinsta, we take a multi-layered approach to keep your website secure, especially from threats like DDoS attacks. Central to our protection strategy is our integration with Cloudflare.

All traffic for sites hosted on Kinsta passes through Cloudflare, where a powerful WAF filters it. The WAF automatically blocks harmful requests, including DDoS attacks, before they can reach your site.

For example, we reported how we managed to serve 75.51 billion requests through Cloudflare in just one month, of which 3.3 billion were mitigated by Cloudflare’s Web Application Firewall (WAF). This shows the effectiveness of Cloudflare’s DDoS protection in filtering out malicious traffic.

Our defense doesn’t stop with Cloudflare. We also use GCP’s firewall as a second layer of protection, and we have internal systems that look at abusive trends across our infrastructure that may block patterns deemed to be harmful. This ensures overall platform stability.

Additionally, our SysOps team constantly updates firewall rules based on specific issues or threats. We manage these updates in-house to ensure top-notch security and don’t offer manual control over these rules through customers’ MyKinsta dashboards.

For customers with unique needs, we recommend having their WAF solution in front of our infrastructure using WAF providers like Sucuri and Wordfence.

3. Backup and recovery plans

Backups are your safety net. In the event of a cyberattack, server failure, or accidental data loss, having a reliable backup ensures that you can restore your website quickly and avoid prolonged downtime or permanent loss of important data.

But backups are only as good as the frequency with which they’re made and how easily they can be restored. When choosing a host, it’s important to know what backup and recovery options are available and how they protect your data.

What to ask:

  • How often are backups performed, and where are they stored?
  • What is the process for restoring data in case of a breach or loss?
  • Are backups encrypted and stored off-site to prevent loss in case of a local disaster?

Why it matters:

Frequent, automated backups ensure you don’t lose critical website data due to unexpected issues like a breach, server crash, or user error. Knowing that backups are performed daily or more frequently provides peace of mind that you can restore your site to a recent version without significant data loss.

The location of backup storage is also important. Storing backups in a secure, off-site location means your data remains protected even if there’s a problem with the primary server or data center. Encrypting backups ensures that your sensitive data remains safe even if they’re intercepted.

Finally, ease of restoration is key. If something goes wrong, the ability to quickly and easily restore a backup without technical complications or delays is crucial to minimizing downtime and keeping your site running smoothly.

Having a clear understanding of your web host’s backup and recovery plans helps ensure that, no matter what happens, you can restore your site with minimum disruption.

How we handle backup and recovery at Kinsta

At Kinsta, we understand the critical importance of having reliable backups. That’s why we offer a comprehensive backup solution that ensures you can quickly recover your site in case of an emergency.

We offer the following types of backups:

  • Automatic daily backups: We provide automatic daily backups for all WordPress sites hosted on our platform. These backups capture a complete snapshot of your site, including files, databases, redirects, and MyKinsta settings. This means that if something goes wrong, you can easily restore your site to its previous state with just a few clicks in MyKinsta.
  • Manual and hourly backups: When making significant changes to your site, you can create up to five manual backups, ensuring you have restore points exactly when you need them. Additionally, we offer an hourly backup add-on for users who need even more frequent restore points — ideal for eCommerce sites or other dynamic environments where data changes often.
  • External backups: We offer an external backups add-on that allows you to back up your site to Google Cloud Storage or Amazon S3. This off-site backup option adds an extra layer of security, making it easy to incorporate these backups into your broader disaster recovery strategy.
  • Downloadable backups: We also allow you to create and download a backup of your site in a ZIP file once per week. This backup includes your site’s files and database, allowing you to keep a copy offline for extra security.

At Kinsta, we also know the importance of easy backup restoration. In MyKinsta, the process is quick and simple whether you need to restore to your live environment or a staging site. If you ever need to undo a restoration, a new backup is automatically created before the restore, giving you flexibility and control over your site’s state.

Also, depending on your plan, backups are retained for up to 30 days, ensuring you have ample restore points to choose from if something goes wrong. We offer extended retention periods for those on our higher-tier plans, providing even greater peace of mind.

4. Access control and authentication

Controlling who can access your website’s backend and server environment is crucial for maintaining security.

Unauthorized access can lead to data breaches, site defacement, or compromise. Implementing strong access control measures and secure authentication methods is essential to protecting your site.

When evaluating a hosting provider, understanding how they manage access control and authentication can give you confidence that your site is well-protected from unauthorized users.

What to ask:

  • What access control measures are in place to prevent unauthorized access to my account and server?
  • Does the host support multi-factor authentication (MFA) for accessing the control panel, FTP/SFTP, and SSH?
  • How are permissions managed for multiple users or team members?

Why it matters:

Strong access control is the foundation of your website’s security. Without proper access controls, unauthorized users could gain entry to your site’s backend, potentially leading to data theft, unauthorized changes, or even complete site takeover.

Effective access control involves limiting who can access your site and ensuring that those with access use secure, up-to-date authentication methods.

MFA is a key component of secure access control. By requiring a second form of verification — such as a text message code or authentication app — in addition to a password, MFA adds an extra layer of protection against unauthorized access. This is especially important for critical areas like your hosting control panel and FTP/SFTP and SSH access, where a breach could have severe consequences.

Managing permissions effectively is also essential, particularly for sites with multiple users or team members. A well-structured permission system ensures that users only have access to the areas of the site they need, reducing the risk of accidental or malicious changes.

It’s important to understand how your hosting provider handles user permissions and whether they offer tools to help you manage access across your team.

How we handle access control and authentication at Kinsta

Kinsta is a managed WordPress hosting solution that provides a custom-built cPanel alternative for managing your sites. This dashboard offers many features that are not available in the cPanel while being easier to use.

We use Role-Based Access Control (RBAC) in MyKinsta. This means you can assign different access levels to team members based on their roles, ensuring that each person only has access to what they need. For example, a WordPress Site developer might have access only to staging environments, while a Company Administrator can manage the entire company account. This level of control minimizes the chances of unauthorized changes and keeps sensitive areas restricted to the right people.

Choose the services and user roles you want your user to access
Choose the services and user roles you want your user to access.

Dashboard security is strengthened by 2FA, which is available to all users in MyKinsta. This extra step, requiring users to verify their identity with a code from an authenticator app, ensures that access to the account is protected even if a user’s password is compromised. It’s a simple yet powerful layer of defense that helps secure your website and account.

Additionally, we support Single Sign-On (SSO) using OAuth 2.0 via GitHub. This allows you to log in to MyKinsta securely with your GitHub credentials, making the login process smoother while maintaining strong security standards.

On the infrastructure side, we use GCP’s Identity and Access Management (IAM) system to manage internal access to our servers. This system ensures that our internal team members only have the minimum access they need to perform their tasks. By sticking to the principle of least privilege, we minimize the risk of unauthorized access to our infrastructure, ensuring that your site remains protected by multiple layers of security.

For secure backend access, we provide SSH and SFTP connections, with credentials managed in MyKinsta. You can enhance security by setting password expiration intervals, restricting access by IP address, or enabling SSH key-only access.

Additionally, you can disable SFTP/SSH access when not needed and adjust password controls, giving you full control over how and when access is allowed, ensuring your site’s environment remains secure.

Kinsta SFTP/SSH access information
Kinsta SFTP/SSH access information.

5. Malware detection and removal

With so many plugins, themes, and software components, vulnerabilities can easily appear in a WordPress site, especially when these elements become outdated. This increases the risk of malware (malicious software) infections, leading to serious consequences like data theft, site defacement, or even losing control of your website.

Detecting and removing malware swiftly is critical to maintaining your website’s security and reputation. That’s why it’s essential to understand how your hosting provider handles malware detection and removal.

What to ask:

  • Does the hosting provider offer automatic malware scans, and how often are they performed?
  • What happens if malware is detected, and how is it removed?
  • Can I add additional tools or plugins for enhanced malware protection?

Why it matters:

Malware infections can compromise your site’s security and reputation, leading to loss of customer trust and even search engine penalties. This is why regular, automated malware scans are essential. They help you detect threats early, allowing for prompt action before they cause significant damage. If malware is found, having a clear and efficient removal process is key to quickly restoring your site to a clean state.

Additionally, having the option to add your security tools or plugins can further strengthen your defense.

Knowing how your host handles malware detection and removal will give you peace of mind that your site is continuously monitored for threats and can be quickly cleaned if an infection occurs.

How Kinsta handles malware detection and removal

At Kinsta, we monitor your sites 24/7, scanning for malicious code and potential threats. Our proactive approach ensures we catch malware early before it can cause serious damage. In the event that malware is detected or a site is compromised, we take swift action to clean up the infection.

Our security pledge guarantees that if your WordPress site is hacked while hosted with us, we’ll work with you for free to remove the malware and restore your site. This includes a deep scan of your site’s files, identification of the source of the infection, and removing any affected plugins or themes.

Our container-based hosting infrastructure also prevents cross-contamination between sites at the server level, providing additional peace of mind that your other sites remain unaffected. You can also use popular WordPress security plugins like Sucuri and Wordfence.

6. Uptime monitoring and response

When your website goes down, it can have serious consequences for your business — lost revenue, damaged reputation, and frustrated users. Uptime monitoring is crucial to ensure your site remains online and accessible to visitors.

A hosting provider must offer good uptime performance, robust monitoring systems, and a rapid response plan to address any downtime.

What to ask:

  • Does the hosting provider offer 24/7 uptime monitoring?
  • How quickly do they respond to downtime, and what is their process for getting the site back online?
  • Is there a guaranteed uptime percentage in their service-level agreement (SLA)?

Why it matters:

Website downtime can be costly. When your site is offline, you lose potential sales or engagement, your SEO ranking can also suffer, and your brand’s reputation may suffer. That’s why uptime monitoring is essential.

Continuous monitoring ensures that downtime is immediately detected, allowing the hosting provider to take quick action and minimize the impact.

A good hosting provider will have systems in place to monitor uptime 24/7 and a dedicated team ready to respond to problems. In addition, a guaranteed uptime percentage — such as 99.9% — in a service-level agreement (SLA) assures that the host is committed to keeping your site running smoothly.

Knowing how your provider handles uptime monitoring and their response to downtime is key to ensuring your site’s reliability and availability.

How we handle uptime monitoring at Kinsta

Kinsta prioritizes uptime by monitoring the status of every WordPress site on our platform every three minutes. This frequent monitoring ensures that we detect issues as soon as they arise. If a site fails to load, our engineers are immediately alerted and respond quickly to restore service.

In addition to our internal response, we notify you directly if critical issues persist over consecutive checks. This includes site errors, DNS misconfigurations, SSL certificate problems, and domain expiration. These proactive notifications help you stay informed and act swiftly if needed.

Thanks to the strength of our infrastructure, our platform is backed by a 99.9% uptime guarantee through our Service Level Agreement (SLA).

7. Logging and activity tracking

In addition to uptime monitoring, detailed logging allows you to track every action and event happening on your website. This helps in troubleshooting, auditing, and maintaining the security of your site by keeping a record of user activities, data access, and server performance.

What to ask:

  • Does the host offer activity logs to track user actions and data access?
  • Can I access server logs for troubleshooting and performance monitoring?
  • How long are logs stored, and are they easily accessible?

Why it matters:

Logging is essential for maintaining your site’s security and performance. Activity logs allow you to track who did what and when, which is crucial for detecting unauthorized actions or pinpointing the cause of an issue. Access to server logs is also important for troubleshooting server-level problems, diagnosing errors, and monitoring resource usage.

A good hosting provider will offer easy access to user activity and server logs, ensuring you have the tools to monitor your site’s health and security.

How Kinsta handles logging and activity tracking

Kinsta provides detailed activity logging and server logs to give you full visibility over your site and account. With the activity log, you can track all key actions performed within MyKinsta, like site changes or updates, and see who initiated them and when. This is especially useful for monitoring team activities and quickly identifying any issues.

For troubleshooting, our platform gives you access to important server logs, including error logs and access logs, directly through the MyKinsta dashboard.

These logs help you diagnose issues like PHP errors, cache performance, or server requests, making it easier to resolve problems quickly. Additional logs, like cache-purge and mail logs, are available via SFTP for more advanced diagnostics.

Our platform also sends real-time notifications to inform you of system status, so you’ll always know if platform-wide issues arise.

8. Security audits and compliance

Security audits and compliance checks ensure your website meets industry standards and follows best practices for protecting sensitive data.

Regular security audits identify vulnerabilities and weaknesses in your system, while compliance with security frameworks ensures that your site follows the necessary regulations, especially for businesses handling personal data or financial information.

Knowing how your hosting provider handles security audits and compliance is essential to maintaining a secure and compliant website.

What to ask:

  • Does the hosting provider conduct regular security audits on its infrastructure?
  • Is the host compliant with industry security standards and regulations (such as SOC 2, GDPR, PCI DSS)?
  • What security certifications does the hosting provider have, and how often are they renewed?

Why it matters:

For businesses that handle sensitive data, compliance with regulations like GDPR, PCI DSS, or SOC 2 is essential for avoiding fines and maintaining customer trust.

Hosting providers that conduct regular audits and maintain compliance with industry standards show a commitment to maintaining a secure environment. Certifications like ISO 27001 and SOC 2 demonstrate that the host follows strict security protocols and undergoes regular checks to ensure ongoing security.

By understanding your host’s approach to security audits and compliance, you can rest assured that your website meets both security best practices and regulatory requirements, reducing the risk of breaches and ensuring data protection.

How we handle security audits and compliance at Kinsta

At Kinsta, we take security and compliance seriously, ensuring that our platform meets industry-leading standards. To maintain our compliance with SOC 2 Type II and ISO 27001, we undergo annual security audits conducted by independent agencies, including BARR. These reports, updated annually, demonstrate our commitment to safeguarding your data and infrastructure.

Our compliance doesn’t stop there. We are also certified for ISO 27017 and ISO 27018, reinforcing our adherence to best practices for cloud security and protecting personal data in cloud computing environments.

Kinsta trust page
Kinsta trust page.

Additionally, we emphasize Data Leak Prevention (DLP) and Data Rights Management. Our system is designed to align with your organization’s Information Security Policy, ensuring that sensitive data is protected against unauthorized access or exposure.

Our Data Processing Addendum (DPA), part of our terms of service, outlines how we handle your data, ensuring compliance with regulations like GDPR and CCPA. This includes how data is processed, stored, and protected, giving you peace of mind that your data is safe and secure.

By leveraging (GCP) and Cloudflare, we ensure that our infrastructure meets the highest security standards. GCP’s infrastructure is independently assessed for compliance with PCI DSS 3.2 requirements, adding another layer of trust and security to our hosting platform.

With these certifications and regular audits in place, we assure you that your site is hosted on a secure, compliant platform that consistently meets the most stringent industry standards.

You can learn more from our trust page.

Summary

This checklist is not exhaustive but covers many essential aspects of hosting security. You can understand how your hosting provider handles security by focusing on key areas like data protection, DDoS prevention, uptime monitoring, and compliance.

Asking these questions helps ensure that your business is protected from common threats and aligned with best practices for data security and privacy.

Being proactive about security will give you confidence that your website is safe, allowing you to focus on growing your business.

If you believe Kinsta meets your security needs and you’d like to learn more about our pricing to find the best plan for your business, contact our sales team.

The post What to ask your web host about security: A checklist for business owners appeared first on Kinsta®.

]]>
https://kinsta.com/blog/website-security-checklist/feed/ 0
Developing CSS custom properties with theme.json for enhanced WordPress themes https://kinsta.com/blog/css-custom-properties-theme-json/ https://kinsta.com/blog/css-custom-properties-theme-json/#respond Tue, 01 Oct 2024 14:10:51 +0000 https://kinsta.com/?p=184925 WordPress theme developers can use a theme.json file to streamline a process that used to rely largely on PHP. However, you can still use your HTML, JavaScript, ...

The post Developing CSS custom properties with theme.json for enhanced WordPress themes appeared first on Kinsta®.

]]>
WordPress theme developers can use a theme.json file to streamline a process that used to rely largely on PHP. However, you can still use your HTML, JavaScript, and PHP skills to build your themes — and CSS is no exception. In fact, you use CSS custom properties within theme.json. This can enhance the design stage and offer greater flexibility.

In this guide, we tackle CSS custom properties head-on to explore how they work alongside WordPress and theme.json. But before we get there, let’s summarize theme.json, full site editing (FSE), and how CSS fits into this new design approach.

How theme.json works with WordPress

The theme.json file first appeared in WordPress 5.8. It’s a revolutionary way to design WordPress themes, using JSON syntax to build a configuration file. WordPress reads this and applies the results without the need for much PHP, CSS, or JavaScript.

A code editor window showing the contents of a theme.json file for a WordPress theme. The JSON structure defines theme settings, including schema versions, patterns, and color settings. In the background, a scenic landscape with mountains, forests, and terraced fields is visible.
A theme.json file within a code editor.

The global settings and styles within FSE control various visual aspects of your theme. These can include typical color palettes and typography, but they can also include layout options and individual Block and element styles.

While FSE is intuitive, powerful, adaptable, and easy to use, theme.json can help bridge the gap between the end user and developer roles. Almost every option theme.json gives you is also visible within the Site Editor.

The WordPress Site Editor interface, showing the home page of a website on the right-hand side of the screen, while the black, left-hand sidebar gives options for navigation, styles, pages, templates, and patterns.
The main Site Editor interface within WordPress.

Using theme.json offers many advantages when building WordPress themes. There are a few reasons for this:

  • You have a central location for your theme’s design configuration, which makes it easier to manage and update.
  • There’s less obfuscation between the front-end experience, Site Editor, and a theme’s codebase.
  • Using theme.json offers compatibility with the future of WordPress development and design.
  • The built-in functionality of WordPress means you reduce the need for the user to apply custom CSS.

Let’s take a look at how theme.json relates to FSE’s global settings and styles.

A primer on FSE’s Global Settings and Styles

FSE represents a new era of WordPress theme development, and Global Settings and Styles are at the forefront. This allows users to customize almost every aspect of a site’s appearance through the Site Editor functionality.

The WordPress Site Editor showing the Styles panel's input fields in the right-hand sidebar. It lets you make adjustments to typography settings. The left-hand side shows a partial view of a blue-themed webpage.
The Styles panel within the WordPress Site Editor.

Here, you can adjust aspects of your theme’s layout with options that used to require CSS or a third-party page builder plugin. Modifying margins, padding, and borders are examples, but there are plenty more.

The WordPress Site Editor, showing the Layout customization panel. It lets you customize content dimensions, padding, and block spacing. The left-hand side of the screen shows a partial view of a blue-themed webpage.
Working with typical CSS elements like padding and margins within the Site Editor.

You can even enable or disable much of this functionality within theme.json (or a Block’s own block.json file). This supports UI customization alongside the overall site design.

However, the options at your disposal — while extensive — might not cover every need. This will be especially true if you build a theme from scratch. This is one job CSS custom properties can help solve.

Understanding CSS custom properties

In PHP, JavaScript, and almost every programming language, variables hold the values of various elements in your code. For instance, you can store values such as names, dates, and numbers and use them throughout your program.

CSS3 variables — or CSS custom properties as we call them throughout this post — are supported by most current browsers. Internet Explorer doesn’t support them, nor does Opera Mini. Still, the major players all do.

A compatibility chart for CSS Variables (Custom Properties) across different web browsers. The chart shows high global usage at 97.05 percent and indicates widespread support across major desktop and mobile browsers.
The Can I Use website shows the current support for CSS custom properties.

CSS custom properties let you store values to reuse throughout your stylesheet. It’s a powerful way to create more dynamic and flexible CSS. You can update multiple style rules by changing a single value.

The concept of CSS variables isn’t entirely new. Preprocessors such as Sass use similar functionality. For instance, take the following Sass:

$font-stack: Helvetica, sans-serif
$primary-color: #333

body
  font: 100% $font-stack
  color: $primary-color

This processes into typical CSS:

body {
  font: 100% Helvetica, sans-serif;
  color: #333;
}

However, CSS custom properties take this directly to the browser. This offers some advantages:

  • Dynamic updates. Unlike most preprocessor variables, you can update CSS custom properties “on the fly” using JavaScript.
  • Cascading nature. Custom properties will follow the CSS cascade, which gives you greater flexibility and more context-aware styling.

Custom properties will also be more performant by reducing code redundancy. Smaller stylesheets mean faster loading times.

The syntax for CSS custom properties

As with typical preprocessor variables, the syntax for CSS custom properties is straightforward. It uses double hyphens rather than dollar signs to specify a property:

:root {
  --primary-color: #007bff;
}

From there, you use the var() function to assign those properties to elements:

.button {
  background-color: var(--primary-color);
}

Note that you can also assign custom properties using the @ property. However, as you’ll understand shortly, WordPress simplifies this whole process.

Where you can use CSS custom properties

Versatility is the order of the day when it comes to CSS custom properties. With WordPress and theme.jsonYou have a few ways to use them:

  • Presets: You can define color, font, and spacing presets.
  • Block styles: Individual Blocks can use custom properties for consistent styling.
  • Global styles:  Custom properties are invaluable for site-wide design.

You can create completely custom properties for whatever purpose you wish. Let’s look at a practical example of how you might use custom properties in your theme.json file:

{
  "settings": {
    "color": {
      "palette": [
        {
          "slug": "primary",
          "color": "#007bff",
          "name": "Primary"
        }
      ]
    },
    "custom": {
      "line-height": {
        "body": 1.5,
        "heading": 1.2
      }
    }
  },
  "styles": {
    "typography": {
      "lineHeight": "var(--wp--custom--line-height--body)"
    },
    "blocks": {
      "core/heading": {
        "typography": {
          "lineHeight": "var(--wp--custom--line-height--heading)"
        }
      }
    }
  }
}

Here, we define a color preset and use the custom property to define line-height values for the pages headings and body. WordPress will generate CSS properties for the elements you define using custom. Further down, we can assign these custom properties to various styles, settings, Blocks, and more.

The benefits of using CSS custom properties

You may already have ideas about how CSS custom properties can help you when developing themes. Even so, there are plenty of benefits to note.

We already talk about modularity and reusability. All of the common values you define as custom properties will promote consistency and reduce redundancy. That redundancy will translate into better potential performance for your theme.

For the end user, custom properties provide several advantages:

  • Simplified customization. Users and site owners can customize a theme without the need for complex CSS knowledge. Once you expose variables through theme.json, users can access the settings through the Site Editor.
  • Better compatibility with FSE. Custom properties align with FSE principles, allowing you to create more flexible and dynamic theme designs.
  • Easier maintenance and updates. If you need to update common values across your theme, a custom property means changing it in just one place. It streamlines your maintenance and makes updates and tweaks more manageable.

Overall, custom properties can improve your theme development workflow. Determining them is also more straightforward than using typical CSS variables.

How to define CSS custom properties within theme.json

Let’s get into the practical aspects of defining and using CSS custom properties within theme.json. The first step is learning how to write them.

Syntax and naming conventions

WordPress offers the custom property to help with definitions. This is slightly easier to use than the @ property or definitions within pseudo classes, and uses the standard key/value format:

{
  "settings": {
    "custom": {
      "property-name": "value"
    }
  }
}

Behind the scenes, WordPress will process this definition and generate a CSS custom property using double hyphens:

--wp--custom--<custom-element>

--wp--custom-- will always be a part of your CSS property, and it won’t use camel case. For instance, if you define lineHeight as a custom property, WordPress will turn it into “kebab case:”

--wp--custom--line-height

When it comes to naming conventions, you can use camel case if you wish, although we advise kebab case for your custom property names. This is consistent with WordPress’s naming conventions, improves readability, and cuts down on processing errors.

Note: CSS custom properties use double hyphens because the W3C’s CSS Working Group also wants to encourage you to use Sass (which uses dollar signs to define properties). This way, you have the option of both to enhance your designs.

WordPress already defines some custom properties — or at least, themes have that option to do so. This means you’ll see CSS variables within theme.json without an explicit declaration:

{
  "settings": {
    "color": {
      "palette": [
        {
          "slug": "primary",
          "color": "var(--wp--preset--color--primary)",
          "name": "Primary"
        }
      ]
    },
    "custom": {
      "spacing": {
        "small": "1rem",
        "medium": "2rem",
        "large": "3rem"
      }
    }
  },
  "styles": {
    "spacing": {
      "blockGap": "var(--wp--custom--spacing--medium)"
    }
  }
}

In this example, we define a primary color using an existing preset color. Then, we define some custom spacing properties and then set them using var().

This means we don’t need to hard-code values into theme.json. What’s more, users can update these values within the Site Editor and have them propagate throughout the theme.

Presets vs. custom properties

Of course, theme.json also lets you define presets for colors, font sizes, and other common theme elements. On the other hand, you can use custom properties for any value you want to reuse throughout your theme.

The biggest difference here is in naming conventions and accessibility. Users won’t be able to access custom properties in the Site Editor without further work on your end. With presets, WordPress will generate CSS that looks similar to how it processes custom properties:

{
  "settings": {
    "color": {
      "palette": [
        {
          "slug": "primary",
          "color": "#007bff",
          "name": "Primary"
        }
      ]
    },
    "custom": {
      "fontFamily": {
        "base": "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif",
        "headings": "'Helvetica Neue', Helvetica, Arial, sans-serif"
      }
    }
  }
}

Once WordPress processes this, you can see the inherent differences:

--wp--preset--primary: #007bff;
--wp--custom--font-family--base: "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif";
--wp--custom--font-family--headings: "'Helvetica Neue', Helvetica, Arial, sans-serif";

Notice that further property nesting will use double hyphens, even after converting camel case to kebab case.

Global and Block-specific CSS versus CSS custom properties

With classic WordPress, you would use additional and custom CSS on the front end to design elements within your theme. This is still the case with theme.json and FSE, although the approach is different from CSS custom properties.

If you visit the Site Editor and head into the Styles screen, you’ll spot the Additional CSS section. This acts much like a Custom CSS panel within classic WordPress installations:

A partial view of the WordPress Site Editor showing links to the Blocks and Additional CSS settings. The left-hand side of the screen displays a partial view of a building against a blue sky.
The Additional CSS section within the WordPress Site Editor.

This represents a way to add global CSS customization to a theme. However, it’s really a way to give users the ability to add CSS. You might also use this to make small, minor changes that don’t warrant a whole stylesheet.

Within theme.json, you use the css property to define any extra CSS you want to add:

{
  "version": 3,
    "styles": {
      "css": "margin: 0"
    }
}

Note that you don’t need to use semicolons to end CSS statements. You’re also able to set custom CSS for Blocks, too:

{
  "version": 2,
  "styles": {
    "blocks": {
      "core/post-title": {
        "css": "letter-spacing: 1px;"
      }
    }
  }
}

Any time you set CSS like this within theme.json, you will see it within any Site Editor Additional CSS fields. However, remember that nothing you declare using css is a CSS custom property.

Using the ampersand (&) selector

Much like Sass, WordPress also supports the ampersand selector, with a few differences. In this case, it’s a great way to target nested elements and properties. This could be relevant if you choose to declare CSS custom properties for individual Blocks.

For example, take the following:

…
"styles": {
  "blocks": {
    "core/table": {
      "css": "color:#333 & th{ background:#f5f5f5; }"
    }
…

This defines a text color and a background color to the table header element. Once WordPress processes it, you get clean, plain CSS:

.wp-block-table > table {
  color: #333;
}

.wp-block-table > table th {
  background: #f5f5f5;
}

Ampersand selectors are excellent if you wish to extend the CSS you target. An understandable way to think of the selector is that it helps separate your CSS elements. Take the following, for example:

{
  "version": 3,
  "styles": {
    "blocks": {
      "core/avatar": {
        "css": "& img {border-radius: 999px}"
      }
    }
  }
}

This adds a border radius to an avatar and outputs the CSS as you’d expect:

.wp-block-image img {
  border-radius: 999px;
}

However, without the ampersand, WordPress would conjoin your declarations:

…
​​.wp-block-imageimg
…

Using the ampersand selector for your CSS custom properties will be something you do on a regular basis.

Kinsta’s role in supporting modern WordPress development

Your choice of hosting is just as important as any coding language, preprocessor, or other technical element. Without a quality hosting provider at your side, you won’t be able to benefit from the performance and toolset of theme.json or FSE.

Kinsta can be central to your entire workflow, thanks to our development tools. You can start with DevKinsta — our local development environment that uses Docker containers to isolate your WordPress installation:

The DevKinsta interface showing the database and WordPress configuration settings. It displays connection details, including host, port, database name, and WordPress version. The interface also shows options to enable debugging and auto-updates for WordPress.
The main DevKinsta interface.

One useful piece of functionality is DevKinsta’s ability to push and pull data between your local machine and your Kinsta staging environments:

A partial view of the DevKinsta interface displaying site information and control options. The interface shows buttons for opening the site, syncing, accessing the database manager, and WordPress admin. A drop-down menu reveals options to push to or pull from Kinsta. The site type is listed as WordPress, with visible yet partial information about the host.
The options to push to or pull from Kinsta within DevKinsta.

This lets you test your themes in a production-like setting before you begin to distribute them. When working with CSS custom properties, you can ensure they work across different contexts. Kinsta’s API can support your CI/CD pipeline when you are ready to go live.

Other aspects of Kinsta’s architecture will help you across your entire development setup. For instance, Kinsta supports Git, which makes it easy to version control your theme files, including theme.json. For iterating custom properties, or simply experimenting with different configurations, you’ll want to know you have a rollback option.

Finally, if you choose to use your theme on a Kinsta server, our Edge Caching increases the performance of theme.json by up to 80 percent. Having a website that runs fast regardless of the user’s browser will make sure those custom additions display promptly.

Summary

Just as theme.json is a powerful configuration file for creating flexible and maintainable WordPress themes, CSS custom properties are crucial to the workflow. This is how you’ll build and declare CSS for elements the Site Editor doesn’t reach. It will also be key if you build your own Blocks or simply want to develop unique WordPress themes with the ultimate customization depth. What’s more, you also have the option to share that CSS with users through the Site Editor.

Will CSS custom properties be a part of your theme development workflow? If so, how will you use them? Share your insights in the comments section below!

The post Developing CSS custom properties with theme.json for enhanced WordPress themes appeared first on Kinsta®.

]]>
https://kinsta.com/blog/css-custom-properties-theme-json/feed/ 0
What WordPress developers need to know about the blocks property in theme.json https://kinsta.com/blog/theme-json-blocks-property/ https://kinsta.com/blog/theme-json-blocks-property/#respond Thu, 26 Sep 2024 14:06:09 +0000 https://kinsta.com/?p=184906 The introduction of full site editing (FSE) in WordPress highlights the growing importance of the theme.json file. There is now a whole new hierarchy and structure ...

The post What WordPress developers need to know about the blocks property in theme.json appeared first on Kinsta®.

]]>
The introduction of full site editing (FSE) in WordPress highlights the growing importance of the theme.json file. There is now a whole new hierarchy and structure to understand, along with the various properties to help you create your designs. In particular, the blocks property in theme.json is essential if you want to create modern, flexible WordPress themes with unique Blocks.

In this guide, we explore the ins and outs of the blocks property in theme.json so that you can work with, design, and style Blocks to create more dynamic and customizable WordPress experiences.

Understanding the blocks property in theme.json

Before we dive into the intricacies of the blocks property, let’s first understand its role within theme.json and WordPress theme development.

A code editor window displaying a portion of a theme.json file for a WordPress theme. The JSON structure defines custom templates for "blank," "blog-alternative," and "404" pages. The editor has a dark theme with syntax highlighting, and the background shows a misty forest landscape.
Twenty Twenty-Three’s theme.json file.

First, theme.json is the configuration file that lets you define global styles and settings for your themes. This “central hub” lets you control various aspects of your theme’s appearance and behavior, including typography, colors, and layout options. However, it can do more than simply give you programmatic cosmetic tweaks.

The blocks property lets you apply granular control over individual Block types rather than the site as a whole. You can define default styles, settings, and behavior for specific Blocks, which ensures consistency across your theme and flexibility for site owners.

The relationship between the blocks property and full site editing

FSE is a more visual approach to building your site with Blocks at the core. On the front end, you have most of the styling and customization options available to your overall site:

The WordPress Site Editor main screen, showing a blue home page with the title, "A commitment to innovation and sustainability." The page features a modern architectural image and customization options in a black left-hand sidebar.
The full site editing interface within WordPress.

The blocks property is a crucial part of the theme.json file for a few reasons:

  • It provides a standardized way to define block styles and settings.
  • You’re able to create cohesive design systems from a programmatic base.
  • You can offer greater control over the appearance of Blocks without the need for custom CSS.
  • The property helps you create Block patterns and templates.

Developers can use the blocks property to create themes that make the most of full site editing.

How to structure the blocks property (and its syntax)

The standardization that the blocks property provides helps when it comes to structure and syntax. You’ll always nest it within the settings object:

{
"version": 3,
  "settings": {
    "blocks": {
      "core/paragraph": {
        "typography": {
          "fontSizes": [
            {
              "name": "Small",
              "slug": "small",
              "size": "13px"
            },
            {
              "name": "Medium",
              "slug": "medium",
              "size": "20px"
             }
           ]
…

The example above defines custom font sizes for a Paragraph Block. Breaking down the key components is simple:

  • You nest the blocks property under the settings object.
  • Each block type has a namespace and name (core/paragraph here).
  • You then specify the Block’s settings within the object.

The settings include most of what is available for global styles. For instance, they can include typography, color, spacing, and many others.

Configuring global block settings

Let’s see how to define global settings and then look at how this impacts the blocks property. This is how you’ll establish a foundation of consistent design across your theme.

{
"version": 3,
  "settings": {
    "typography": {
      "fontSizes": [
        {
          "name": "Small",
          "slug": "small",
          "size": "13px"
        },
        {
          "name": "Medium",
          "slug": "medium",
          "size": "20px"
        }
…

In this example, we define the global font sizes available to all blocks. Within the WordPress Site Editor, you can find these options as part of the Typography > Elements > Text screen:

The WordPress Site Editor showing the Styles panel options for text. It displays font selection and customization options for Font, Size, Appearance, Line Height, Letter Spacing, and Letter Case.
Most of the theme.json typography settings are accessible within the Site Editor, too.

Each font size you define within theme.json correlates with one of the sizing options here:

A close-up view of a code editor showing part of a WordPress theme.json file. The visible code defines font sizes, including Small, Medium, and Large with their respective sizes in rem units. The Large size includes a fluid typography setting. The editor uses a dark theme with syntax highlighting against a blurred forest background.
You set the font-size presets within the theme.json file.

Of course, there are many other ways to customize your theme from here. The idea is to create a global design that works in 80% of use cases.

Using the blocks property, you can override those core Block styles to cover the final 20%. The Styles screen within the Site Editor also lets you customize the design settings for each Block:

A close-up of the WordPress Site Editor interface, showing content Block options such as Paragraph, Image, Heading, and Gallery. The main content area displays the site's home page.
The Site Editor lets you edit the settings for all core WordPress Blocks.

This is excellent for end users but of less value to a developer. We are focusing on using theme.json to work with the blocks property.

How to customize individual Block types

While global settings are important to help maintain consistency, the real power lies in the scope of the blocks property for customization. This granular-level setup lets you tailor the appearance and behavior of specific blocks to match your theme’s design, just like the Site Editor

Let’s look at an example of customizing the Heading Block for your theme:

{
"version": 3,
  "settings": {
    "blocks": {
      "core/heading": {
        "typography": {
          "fontSizes": [
            {
              "name": "Small",
              "slug": "small",
              "size": "20px"
            },
            {
              "name": "Medium",
              "slug": "medium",
              "size": "30px"
            },
            {
              "name": "Large",
              "slug": "large",
              "size": "40px"
            }
            ],
            "fontWeight": "bold"
            },
            "color": {
              "palette": [
                {
                  "name": "Heading Primary",
                  "slug": "heading-primary",
                  "color": "#333333"
                },
                {
                  "name": "Heading Secondary",
                  "slug": "heading-secondary",
                  "color": "#666666"
                }
              ]
…

You can see that the attributes reflect how you’d make global changes. Let’s summarize what we’re doing:

  • We define specific font sizes for headings and assign them to size labels.
  • The weight of the font for all headings will simply be bold.
  • Those headings will also get a custom color palette.

This ensures that our headings will have a consistent look throughout the design. We also get to control these elements when we don’t know how the end user will apply them, which further benefits consistent design.

Using the right namespace and slug combination

When calling Block types, it’s crucial you use the correct namespace and slug combination. Without it, your changes won’t apply to the Blocks you want to target.

Each Block has a namespace and a slug. Core WordPress Blocks will typically have the core namespace. The slug will be the Block’s name:

…
"blocks": {
  "core/image": {
…

If you need to know the slug for a Block, you can look at its specific block.json file. You can find this within the wp-includes/blocks directory. Here, you’ll have various folders, each of which contains a block.json file. Within each, the namespace and slug for the Block should be near the top of the file:

A portion of a macOS Finder window showing the contents of the code directory. There's also a portion of a code editor with an open block.json file. The visible code defines properties for a WordPress block named
The block.json file will contain key metadata for each individual Block.

If you browse these directories, you’ll notice that the wp-includes directory has a theme.json file of its own. While this might seem confusing, it’s simple to explain.

Why theme.json includes customized Block settings by default

WordPress’ own theme.json file may seem odd at first, namely because it’s not a theme. However, this is no accident. The primary reason is to support backward compatibility with older versions of WordPress.

For instance, the Button Block sets a border radius:

…
"blocks": {
  "core/button": {
    "border": {
      "radius": true
     }
  },
…

Other Blocks will have similar settings to assist in consistency between different versions of WordPress. However, this can cause issues down the line if it’s something you’re not aware of.

If you try to define global settings and wonder why those changes don’t apply to specific Blocks, backward compatibility could be the answer. Of course, you can override these settings in your own theme.json file without a problem.

Developing custom Blocks with theme.json

The theme.json file is ideal for customizing existing Blocks, but its capabilities extend to custom Block development, too. You can leverage theme.json to define default styles and settings for any of your custom Blocks. This helps you deliver seamless integration with your theme’s design.

First, though, you have to build the Block itself. This is beyond the scope of this article, but in summary, there are a few facets:

  • Scaffolding the Block. This involves setting up a local development environment and creating the file structure for the entire Block.
  • Updating the block.json file. Here, you’ll need to change the Block identity and add supports. The latter are ways to declare the support for specific WordPress functionalities. For instance, you can handle alignment, implement anchor fields, work with various typography settings, and more.
  • Tweak the Block’s JavaScript files. Both index.js and edit.js need code to tell WordPress how the Block functions and to let it appear in the Site Editor.

You may also need to edit render.php, add static rendering, and a whole host of other tasks. At this point, you can apply any stylistic changes to theme.json as with any other Block. For now, let’s take a closer look at block.json.

The block.json file

This file is what the WordPress development team calls the “canonical” way to register Blocks for both the server and client side. The metadata you include here tells WordPress all about the Block type and its supporting files:

{
  "$schema": "https://schemas.wp.org/trunk/block.json",
  "apiVersion": 3,
  "name": "my-plugin/notice",
  "title": "Notice",
  "category": "text",
  "parent": [ "core/group" ],
  "icon": "star",
  "description": "Shows warning, error or success notices...",
  "keywords": [ "alert", "message" ],
  "version": "1.0.3",
  "textdomain": "my-plugin",
  "attributes": {
    "message": {
      "type": "string",
      "source": "html",
      "selector": ".message"
    }
  },
…

It’s akin to the metadata you’d place at the top of a PHP file for themes and plugins. While the file uses JSON data exclusively, you can still share code through PHP, JavaScript, and CSS:

…
"editorScript": "file:./index.js",
"script": "file:./script.js",
"viewScript": [ "file:./view.js", "example-shared-view-script" ],
"editorStyle": "file:./index.css",
"style": [ "file:./style.css", "example-shared-style" ],
"viewStyle": [ "file:./view.css", "example-view-style" ],
"render": "file:./render.php"
…

We come back to this later in the section on variations. To finish this section off, you need to know how to set your custom Block as a default in WordPress. There are a few ways to achieve this. The classic way is to register a custom post type and include the Blocks there. However, there are a couple of other methods.

For example, you could update an existing post type to add a Block template. Here’s a simple example:

…
function load_post_type_patterns() {
    // Define an initial pattern for the 'HypnoToad' post type
    $post_type_object = get_post_type_object( 'hypnoToad' );
    $post_type_object->template = array(
    array(
        'core/block',
…

One more way is to call the default_content hook and define the Block using markup:

function toad_content( $content, $post ) {
    if ( $post->post_type === 'hypnoToad' ) {
        $content ='<!-- wp:columns -->
        <div class="wp-block-columns"><!-- wp:column →
        <div class="wp-block-column"><!-- wp:paragraph -->
        <p></p>
        <!-- /wp:paragraph --></div>
        <!-- /wp:column -->
        <!-- wp:column -->
        <div class="wp-block-column"><!-- wp:paragraph -->
        <p></p>
        <!-- /wp:paragraph --></div>
        <!-- /wp:column --></div>
        <!-- /wp:columns -->';
    }
    return $content;
}
add_filter( 'default_content', 'toad_content', 10, 2 );

Of course, you won’t only use JSON, HTML, and PHP. You’ll also use other languages to help with design and interactivity. The good news is WordPress gives you an uncomplicated way to do so.

Using custom CSS properties for your Blocks

You can achieve a lot using the existing properties, attributes, and objects of theme.json, but it won’t cover every use case. The file gives you the custom property that will help you create relevant CSS properties:

{
"version": 3,
  "settings": {
    "custom": {
      "toad": "hypno"
    }
  }
}

In here, you give a key-value pair, which turns into a CSS variable on the front end:

body {
    --wp--custom--toad: hypno;
}

Note that the variable will use double hyphens to separate its elements. In general, you’ll always see --wp--custom--, which will then tag the key on the end. Sometimes, you’ll define variables and properties with camel case:

{
"version": 3,
  "settings": {
    "custom": {
      "hypnoToad": "active"
    }
  }
}

Here, WordPress will use hyphens to separate the words:

body {
    --wp--custom--hypno-toad: active;
}

Between the custom property and block.json, you have full scope to build your Blocks as you see fit, including any variations you may want to include.

A quick look at Block, style, and Block style variations

Before we move on to styling using the blocks property, let’s look at variations. You have a few different variation types for your designs, and the naming conventions could see you use the wrong type for your needs. Here’s a breakdown of the differences:

  • Block variations. If your Block has alternative versions (think of a Block that will display many custom links set by the user), this is a Block variation. The Social Media Block is a good example of this.
  • Style variations. These are alternative versions of theme.json that work on your global site. We don’t cover this here, but most Block themes offer them for various color palettes and typography settings.
  • Block style variations. This takes the core functionality of style variations and lets you create alternative designs for a Block.

You may wonder whether to use a Block variation or a Block style variation; the answer is uncomplicated. If the changes you want to make can happen within theme.json or using CSS, create a Block style variation. Anything else requires a Block variation.

Block variations

With Block variations, you’ll register them using JavaScript. Creating a file within a theme’s directory is a good idea, but it can go anywhere. It takes one line to register a variation within your JavaScript file:

const registerBlockVariation = ( blockName, variation )

For the blockName, you’ll need to specify the namespace here, too, as you would with the blocks property. Within the variation object, you’ll add the name, title, description, whether the variation is active by default, and more. To load the file in the Site Editor, simply call the enqueue_block_editor_assets hook and enqueue your script within it.

Block style variations

When it comes to Block style variations, you have two options:

  • Use the register_block_style() function with PHP.
  • Create a block-editor.js JavaScript file, use the registerBlockStyle() function similarly to Block variations and enqueue the script.

Once you register a Block style variation, you can target the Block using the variations property:

…
"styles": {
  "blocks": {
    "core/button": {
      "variations": {
        "outline": {
          "border": {
            "color": "var:preset|color|black",
            "radius": "0",
            "style": "solid",
            "width": "3px"
          },
…

This means you may not need any custom CSS at all—almost every aspect of a Block’s design is possible through the blocks property.

Styling a default Block using the blocks property from start to finish

To demonstrate how the blocks property works, let’s walk through a real-world example. Our site uses the Twenty Twenty-Four theme, and is using the default style variation:

The WordPress Site Editor showing a site home page on the right-hand side, with the Styles menu on the left. There are several options to choose an alternative color scheme, along with palette customization options.
Each theme will often come with various style variations that achieve different looks.

So far, this looks ideal to us — although the headings and body text seem too similar in color. We want to change one or both of the colors to differentiate them. As an end user or site owner, we can fix this within the Site Editor’s Styles sidebar. If you head to Blocks > Heading, you can click the Text element and change the color to something more suitable:

The WordPress Site Editor interface showing a website home page. The main content area displays a heading, brief description, and an About us button all in black. Below is an architectural image featuring a modern building with slanted wooden slats. The right-hand sidebar shows the Styles options, with a pop-out panel to select a text color.
You can change individual Block settings with ease from the Site Editor.

However, as a developer, you can do this within theme.jsonLike any other theme, the best approach is to create a child theme to preserve any changes you make. A second advantage is that your theme.json file will look cleaner.

We’ll create a directory within wp-content/themes/ and call it twentytwentyfour-child. Here, add a valid style.css file and a blank theme.json file.

A macOS file explorer window for the twentytwentyfour-child theme showing two files: style.css and theme.json, indicating a child theme setup for WordPress development.
Every child theme directory needs a style.css file and a theme.json file.

From here, you can open the JSON file and get to work.

Creating and populating a theme.json file for the child theme

The main difference between creating a parent and child theme with regards to theme.json is the file’s structure. You won’t need to state the schema or necessarily put everything within the settings object. In our case, we have to use the styles property:

{
"version": 3,
  "styles": {
    "blocks": {}
  }
}

Next, we need to find the namespace and slug for the Heading Block. The official Core Blocks Reference Guide lists all of these and will even tell us what attributes and properties the Block supports. The guide tells us we can tweak the background, gradient, link, and text values for the color property.

"blocks": {
  "core/heading": {
    "color": {}
  }
}

With the structure complete, we can begin to figure out how to restyle the text.

Finding a color scheme and applying the changes

Now, we need a color that suits our needs. The Twenty Twenty-Four default variation has an excellent palette, and checking it in a dedicated contrast checker gives us some ideas:

The Coolors color palette contrast checker tool showing various color combinations with text samples to assess accessibility and readability. One square with a red highlighted box shows two hexadecimal codes of compatible contrasting colors.
Checking your color schemes for the right accessible contrast is a key step in designing a theme.

Next, we can add the color choice for our Block to theme.json. Because the parent Twenty Twenty-Four theme uses custom CSS properties to define palette styles, we can call this here too:

…
"core/paragraph": {
    "color": { "text": "var(--wp--preset--color--contrast)" },
…

If you need to know the name of a palette color, you can find it in the Site Editor from the color picker:

A close-up of the Text Elements color picker interface. It shows a selection of color swatches with hexadecimal color codes, with the Contrast color set as the primary option.
You can find the name of a color by looking at it within a Site Editor color palette.

Once you save your changes, refresh your site, and you should see the new color scheme in place. If not, check that you’re nesting the blocks property within the right object, as this is a common sticking point.

As we look at the site, the text is less contrasting and easier to read. However, we still want to see some definition between the Paragraph Block and the surrounding headings. The theme’s default palette has some other, bolder colors. We’re going to try the Accent / 3 color for the Heading Block:

"blocks": {
  "core/heading": {
    "color": { "text": "var(--wp--preset--color--accent-3)" }
  },
  "core/paragraph": {
    "color": { "text": "var(--wp--preset--color--contrast)" }
  }
}

After saving the changes and refreshing the front end, you’ll see that the Heading Block has more definition:

The WordPress Site Editor showing a site home page including a header image of a modern architectural structure. The main content displays the text "A commitment to innovation and sustainability" in an orange-red color.
The front end changes to the Heading Block based on the theme.json settings.

This doesn’t have to be the end of your editing. You can even customize the Site Editor’s options from theme.json.

Adding attribute options to Blocks

Each Block’s supports determine its options within the Site Editor. For instance, the Paragraph Block defaults to disabling the drop cap functionality.

The WordPress Site Editor showing a close-up of the right-hand options sidebar. The floating Typography customization panel displays options for font, size, appearance, line height, letter spacing, decoration, orientation, and letter case — but no drop cap.
The Site Editor doesn’t let you choose to implement drop caps by default.

We can turn this back on within the theme.json file and blocks property. Looking at the reference material, we can leverage the typography property to enable drop caps:

…
"core/paragraph": {
  "color": { "text": "var(--wp--preset--color--contrast)" },
  "typography": { "dropCap": true }
…

Once we save those changes and refresh the editor, the option to toggle a drop cap will be available to you:

The WordPress Block Editor interface showing a paragraph of Lorem Ipsum text with a large drop cap. There are typography customization options visible on the right-hand sidebar, and the open More elements menu showing the enabled Drop cap option.
Enabling the Drop Cap functionality in the WordPress Site Editor takes seconds with theme.json.

The theme.json file isn’t simply a configuration for design. It can also help add and remove functionality to the Site Editor.

How Kinsta’s managed hosting can support your WordPress theme development

The intricacies of theme development and theme.json rely on quality solutions throughout the development chain to take advantage of the potential for improved performance.

A local development environment is crucial, as this lets you create, manage, and tinker with WordPress sites on your local machine. DevKinsta can help there.

The Site info dashboard within DevKinsta. It displays technical details such as WordPress version, web server, and database type, along with options to manage the site.
The DevKinsta interface.

DevKinsta offers many benefits:

  • It runs on Docker containers, which means you isolate your installation from the rest of your machine. As such, you can test your theme.json configurations and custom Blocks without worry.
  • You can make rapid iterations to your theme.json file and see the results immediately in your local environment.
  • Creating multiple local sites to test your theme across different WordPress versions and configurations is a breeze.

What’s more, you won’t use any of your server’s resources until you’re happy and ready. Kinsta’s staging environments provide an ideal next step. You can create a copy of your production site quickly and even pull it down to your local environment to keep working.

This is a great way to carry out performance testing for your theme, especially when you combine the staging with Kinsta’s Application Performance Monitoring (APM) tool.

You can also leverage Kinsta’s Git integration across all of your environments. This lets you push and pull changes to repos and deploy from there, too.

Summary

Understanding the blocks property in theme.json is a necessary step for all theme developers. This can take a global design and make it more unique, cohesive, and relevant. Having full scope to work with individual core and custom Block settings helps every user leverage the capabilities of full site editing. In addition, having these options available in the Site Editor means end users can make their own changes without code while you present stellar default options.

Do you have any questions about using the blocks property with the theme.json file? Ask away in the comments section below!

The post What WordPress developers need to know about the blocks property in theme.json appeared first on Kinsta®.

]]>
https://kinsta.com/blog/theme-json-blocks-property/feed/ 0