Kinsta® https://kinsta.com/ Fast, secure, premium hosting solutions Thu, 26 Sep 2024 14:40:58 +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 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
How isolated software containers keep your WordPress website secure https://kinsta.com/blog/container-security/ https://kinsta.com/blog/container-security/#respond Tue, 24 Sep 2024 14:47:51 +0000 https://kinsta.com/?p=185029 When searching for a web host, it’s easy to get distracted by attractive pricing, sleek dashboards, and promises of speed. Many hosting providers highlight these aspects, ...

The post How isolated software containers keep your WordPress website secure appeared first on Kinsta®.

]]>
When searching for a web host, it’s easy to get distracted by attractive pricing, sleek dashboards, and promises of speed. Many hosting providers highlight these aspects, often downplaying critical features like security.

This is because people are drawn to visual appeal and affordability without digging deeper into what truly matters — how secure the hosting environment is.

Security should be at the top of your priority list when selecting a host. It’s not just about finding a service that claims to offer security. It’s about understanding how that security is implemented and guaranteed.

For example, many providers offering cheap hosting plans rely on shared hosting environments. They may advertise security alongside affordability and convenience, but they often fail to mention that the technology behind shared hosting can introduce significant security risks, particularly for WordPress sites.

This is where isolated software containers come in. They take a more modern approach to securing websites and avoid the compromises that come with shared environments.

This article helps you understand why isolated software containers offer superior security compared to shared hosting and how they can safeguard your WordPress site.

Why shared web hosting is not the best choice

Shared web hosting has existed for a long time, dating back to the days of basic HTML websites. Users loved the low cost and the large amount of storage they offered. You could easily host several basic sites on a single account, making it easier to live with any shortcomings.

Things have changed. The rise of content management systems (CMS) like WordPress has placed greater demand on hosts.

These days, a host must power a database, process code (such as PHP), and serve large media files. This creates more potential for exploits and breakage, and these sites require more resources and tighter security measures.

Here’s why shared hosting isn’t an ideal choice for modern websites:

  • You share more than server space — Shared hosting accounts share everything. You share the server’s operating system, CPU cycles, memory, and more. There’s no guarantee that your site will always have the resources it needs.
  • Your accounts are not completely private — Other users may not be able to see your account, but a hacker with root access can. From there, they can spread malware across the server and access account and user data.
  • Sharing resources impacts performance — A site using too many resources will impact others on the server, leading to poor or unstable performance. If any site experiences a DDoS attack, this may slow down or even crash other sites on the server.

As an agency, shared hosting can seem like a good deal since you host multiple sites. However, the issues above point to why this is a bad idea. You could end up with hacked sites or be hampered by poor performance.

This negates any pricing advantage you may gain from using shared hosting. The truth is that shared hosting was once all most users needed. However, its best days are over.

Better security through isolated software containers

The security demands of modern websites mean that sharing resources is too dangerous. Web hosts needed to evolve.

New technology was needed to ensure a safer hosting environment. One that allows each site to exist independently of each other.

Isolated software containers are one such solution. They build a virtual wall around each website, mitigating the impact of other sites on the server. They’re also more secure and performant.

Let’s look at how isolated software containers work and why they’re a better option for WordPress.

What are isolated software containers?

An isolated software container is a standalone package that includes everything you need to run an application — like your WordPress website. Each container has dedicated resources, including memory, CPU cycles, and file systems. The only shared resource is the server’s OS kernel.

This setup introduces a more complex environment than shared hosting, requiring a host with expertise in configuring and maintaining these containers securely and efficiently.

How do they work? Here are the components for an isolated software container:

  • Linux containers — are the backbone of most isolated software containers. They allow you to create lightweight, secure environments where applications can run in isolation. Kinsta uses LXC (Linux Containers) and LXD (a container hypervisor) as the underlying container technology for our servers.
  • Secure configuration — Keeping containers isolated and secure requires a carefully configured server. This involves using secure namespaces, which separate different processes, and control groups (cgroups), which allocate resources like CPU and memory. This setup ensures that each container only has access to its allocated resources, preventing interference from other containers.
  • Dedicated resources — Each container includes dedicated resources, ensuring that your application has the CPU cycles, memory, and storage to perform optimally.

At Kinsta, we leverage all the key ingredients of isolated software containers to deliver a high-performance, secure hosting environment.

Each website operates in its isolated container, ensuring that resources like CPU, memory, and storage are allocated exclusively, optimizing performance and stability. This setup allows us to provide a reliable and secure experience for every site we host.

In addition, we integrate with top-tier technologies like Cloudflare and Google Cloud Platform (GCP) to add an extra layer of security and performance. Kinsta uses Cloudflare’s built-in firewall to filter suspicious traffic and prevent DDoS attacks, while our CDN services, powered by Cloudflare, enhance performance with image optimization and HTTP/3 support.

A diagram of Kinsta’s WordPress Hosting
A diagram of Kinsta’s WordPress Hosting architecture.

We also take advantage of encryption. Kinsta only accepts encrypted connections via SSH and HTTPS. We also offer free SSL certificates with wildcard domain support.

For more details on how isolated software containers work, see “Isolated container technology: Everything you need to know.”

How do containers benefit your WordPress website?

We’ve established some key differences between shared and container-based hosting environments. But what does that mean in the real world?

Let’s explore some of the top ways isolated software containers will benefit your WordPress website:

  • Each WordPress install uses a private container — Your WordPress website lives separately from others hosted on the server. Kinsta’s isolated environment ensures that problems from other sites won’t impact yours. Issues like malware and degraded performance won’t spread from one site to another.
  • You won’t share hardware or software resources — Every website has the resources necessary for lightning-fast performance. Kinsta’s platform is built to handle even the most demanding WordPress installs. Everything from e-commerce to enterprise sites will run consistently and predictably.
  • Your site can scale as needed — When your site starts growing and experiencing traffic spikes, isolated software containers make scaling faster and easier. With Kinsta, you can switch plans without experiencing downtime. In addition, we notify you if your account reaches 80% – 100% of its resource consumption. If you have an overage, your site will continue to run as expected.
  • Portability and compatibility with your workflow — Containers make moving your website between hosting environments easy. WordPress core, themes, plugins, and your site’s database are all included. Kinsta’s containers are compatible with continuous integration and continuous deployment (CI/CD) workflows.
  • Easy site backupsContainers allow you to roll back your site quickly. Kinsta offers automated and on-demand site backups, which can be restored using the MyKinsta dashboard and the Kinsta API.

Isolated software containers offer plenty of benefits for WordPress websites. And their flexibility allows them to fit seamlessly into your workflow.

Are isolated software containers a better option for WordPress agencies?

WordPress agencies that host multiple sites can’t afford the risks associated with shared hosting. A security issue on one site can quickly spread to others. It only takes one incident to find yourself in a nightmare scenario.

That’s why isolated software containers are a better deal. They strengthen security and improve performance. They also create long-term stability. That benefits both you and your clients.

Simply put: Isolated software containers are better equipped for hosting WordPress. Here’s why they should be your preferred choice:

  • They’re great for hosting multiple WordPress websites — Since each site has its container, you can host multiple WordPress sites on the same account without worry. Kinsta’s platform is optimized for WordPress’s security and performance needs.
  • They’re easy to manage — You don’t need to sacrifice convenience to use containers. Our MyKinsta dashboard makes it easy to manage multiple WordPress installs. It’s simple to navigate and has the power to perform a wide range of tasks.
  • They provide peace of mind — Containers can be quickly created, moved, backed up, and restored. What’s more, Kinsta automatically backs up your site daily and provides manual backup options. You can rest easy knowing that your client sites are in good hands. If you need help, our support team is here for you 24/7.

Summary

Choosing the right hosting technology helps you get the most out of WordPress. With isolated software containers, you get a combination of security and performance.

You also get all the convenience and flexibility you need. Containers are portable and adapt to your workflow.

Are you ready to level up your site’s security? Find your business’s best WordPress hosting plan, or talk to our sales team.

The post How isolated software containers keep your WordPress website secure appeared first on Kinsta®.

]]>
https://kinsta.com/blog/container-security/feed/ 0
How to continuously deploy your WordPress site to Kinsta with GitHub Actions https://kinsta.com/blog/continuous-deployment-wordpress-github-actions/ https://kinsta.com/blog/continuous-deployment-wordpress-github-actions/#respond Thu, 19 Sep 2024 12:30:43 +0000 https://kinsta.com/?p=185365&preview=true&preview_id=185365 Continuous deployment is an essential part of modern web development. It allows developers to automatically deploy changes from a version control system to a live environment. This approach ...

The post How to continuously deploy your WordPress site to Kinsta with GitHub Actions appeared first on Kinsta®.

]]>
Continuous deployment is an essential part of modern web development. It allows developers to automatically deploy changes from a version control system to a live environment. This approach reduces manual errors and speeds up the development process, ensuring your website is always up-to-date with the latest code changes.

As a Kinsta user, you can use SSH to push changes directly to your server. With GitHub Actions, you can automate the entire deployment process, seamlessly deploying updates to your live site.

This article walks you through setting up continuous deployment for your WordPress site hosted on Kinsta using GitHub Actions. We cover everything from setting up your local environment to pushing changes to GitHub and automatically deploying them to your live site.

Prerequisites

Before you can set up continuous deployment for your WordPress site to Kinsta, there are a few things you need:

  1. Your WordPress site must already be hosted on Kinsta.
  2. You need to pull your site locally. You can either use DevKinsta or download a backup.
  3. A GitHub repository to store and push your site’s code.
  4. Basic knowledge of Git, like pushing code and using a .gitignore file.

Pulling your site locally and setting up GitHub

As a Kinsta user, the easiest way to access your WordPress site’s local files is by using DevKinsta. With just a few clicks, you can pull your site from the Kinsta server into DevKinsta, allowing you to work on your site locally.

To do this:

  1. Open DevKinsta and click Add site.
  2. Select the Import from Kinsta option. This will download everything about your site so you can access it locally for development.

Once your site is available locally, open the site’s folder in your preferred code editor. Before pushing the files to GitHub, add a .gitignore file in the root directory of your project to avoid uploading unnecessary WordPress core files, uploads, or sensitive information. You can use a standard .gitignore template for WordPress. Copy the template’s contents and save it.

Next, create a GitHub repository and push your site’s files to GitHub.

Setting up GitHub secrets for Kinsta

To automate deployment from GitHub to Kinsta, you’ll need some important SSH details, including your username, password, port, and IP address. Since these are sensitive, store them as GitHub secrets.

To add secrets in GitHub:

  1. Go to your repository on GitHub.
  2. Click on Settings > Secrets and variables > Actions > New repository secret.
  3. Add the following secrets:
    • KINSTA_SERVER_IP
    • KINSTA_USERNAME
    • PASSWORD
    • PORT

You can find these details on your site’s Info page in your MyKinsta dashboard.

SFTP/SSH info details in MyKinsta
SFTP/SSH info details in MyKinsta.

With this setup complete, you can now configure automatic deployment for your WordPress site.

Configuring your Kinsta server

Before automating the deployment process with GitHub Actions, you must configure your Kinsta server to receive and deploy code from your GitHub repository.

This involves two steps: creating a bare Git repository on your Kinsta server and setting up a post-receive hook to deploy the latest changes to your live site automatically.

1. Create a bare Git repository on Kinsta

A bare Git repository is a remote destination where GitHub will push your code. This repository doesn’t have a working directory — it’s a central repository designed to receive and store your code.

To do this, first SSH into your Kinsta server using the SSH terminal command available in your MyKinsta dashboard:

SSH terminal command MyKinsta.
SSH terminal command MyKinsta.

Next, navigate to the private folder on your server (or create it if it doesn’t already exist):

mkdir -p /www/your-site/private
cd /www/your-site/private

Here, replace your-site with the actual folder name for your site, which you can find in the path on your dashboard.

Kinsta live site path
Kinsta live site path.

Finally, create the bare Git repository:

git init --bare your-repo.git

For your-repo, you can use the name of your GitHub repository for consistency, but you can name it anything you like.

This bare repository will receive the code pushed from GitHub.

2. Set up the post-receive hook

Once your bare Git repository is ready, setting up a post-receive hook is next. This script will automatically deploy the code to your live site whenever new changes are pushed to the main branch in GitHub.

To do this, navigate to the hooks directory in your bare Git repository:

cd /www/your-site/private/your-repo.git/hooks

Create and edit the post-receive hook:

nano post-receive

Next, add the following script to the post-receive file. This script will check out the latest code into the public directory of your live site:

#!/bin/bash
TARGET="/www/your-site/public"
GIT_DIR="/www/your-site/private/your-repo.git"

while read oldrev newrev ref
do
    BRANCH=$(git rev-parse --symbolic --abbrev-ref $ref)

    if [[ $BRANCH == "main" ]];
    then
        echo "Ref $ref received. Deploying ${BRANCH} branch to production..."
        git --work-tree=$TARGET --git-dir=$GIT_DIR checkout -f
    else
        echo "Ref $ref received. Doing nothing: only the main branch may be deployed on this server."
    fi
done

The script above deploys code from just the main branch. The TARGET variable points to the directory where your live site’s files are located (/www/your-site/public). The GIT_DIR variable points to the bare Git repository.

Save and exit the file by pressing Ctrl + X, then Y, and Enter.

Finally, make the script executable so it can run automatically after each push:

chmod +x post-receive

At this point, the post-receive hook is ready to deploy code automatically whenever changes are pushed to the main branch in your GitHub repository.

3. Generate and add a GitHub personal access token (PAT)

Since GitHub no longer supports password-based authentication, you must use a PAT to authenticate when pushing code to GitHub via SSH. This token will allow GitHub to accept your pushes securely.

To generate the token:

  1. Go to your GitHub account and click on your profile picture, then select Settings.
  2. On the left sidebar, click Developer settings.
  3. Click Personal access tokens > Tokens (classic).
  4. Click Generate new token, and give it a name (e.g., “Kinsta Deployment Token”).
  5. Under Select scopes, check repo (for full control of private repositories).
  6. Click Generate token, and copy the token. (You won’t be able to see it again.)

Next, run the following command to add your GitHub repository as a remote, replacing placeholders with your actual details:

git remote add origin https://your-username:YOUR_PERSONAL_ACCESS_TOKEN@github.com/your-username/your-repo.git

Replace:

  • your-username with your GitHub username.
  • YOUR_PERSONAL_ACCESS_TOKEN with the token you just generated.
  • your-repo with the name of your GitHub repository.

Creating the GitHub Actions workflow for automatic deployment

Now that your WordPress site is on your local machine, pushed to GitHub, and you have set up the necessary GitHub Secrets, it’s time to create a GitHub Actions workflow. This workflow deploys changes to Kinsta automatically whenever you push to the main branch.

To automate the deployment, you’ll create a YAML file that defines how the deployment will happen. Here’s how to set it up:

  1. Create a new directory called .github/workflows in your GitHub repository.
  2. Inside this directory, create a new file called deploy.yml.
  3. Add the following content to the deploy.yml file:
name: Deploy to Kinsta

on:
  push:
    branches:
      - main

jobs:
  deploy:
    runs-on: ubuntu-latest

    steps:
      # Setup Node.js
      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20.x'

      # Checkout the latest code from your repository
      - name: Checkout code
        uses: actions/checkout@v4.1.6

      # Deploy to Kinsta via SSH
      - name: Deploy via SSH
        uses: appleboy/ssh-action@v1.0.3
        with:
          host: ${{ secrets.KINSTA_SERVER_IP }}
          username: ${{ secrets.KINSTA_USERNAME }}
          password: ${{ secrets.PASSWORD }}
          port: ${{ secrets.PORT }}  # Optional, default is 22
          script: |
            cd /www/your-site/private/your-repo.git  # Navigate to the bare Git repository on Kinsta
            git --work-tree=/www/your-site/public --git-dir=/www/your-site/private/your-repo.git fetch origin main  # Fetch the latest changes from GitHub
            git --work-tree=/www/your-site/public --git-dir=/www/your-site/private/your-repo.git reset --hard origin/main  # Deploy changes to the live site

A closer look at this workflow

Here’s a breakdown of the workflow:

  • Trigger: The workflow is triggered every time code is pushed to the main branch of your GitHub repository.
  • Jobs: The workflow contains one job called deploy, which runs on an Ubuntu virtual machine (ubuntu-latest).
  • Checkout code: This step uses the actions/checkout@v4.1.6 action to pull the latest code from your GitHub repository.
  • Deploy via SSH: The appleboy/ssh-action is used to securely connect to your Kinsta server via SSH using the secrets you configured (server IP, username, password, and port). The script within this step runs the following commands:
    • cd /www/your-site/private/your-repo.git: Navigates to the bare Git repository on your Kinsta server.
    • git fetch origin main: Fetches the latest changes from the main branch in your GitHub repository.
    • git reset --hard origin/main: Applies those changes by updating the live site in the public directory where WordPress is hosted.

Testing the workflow

Once you’ve set up the workflow, you can test it by pushing a small change to your GitHub repository’s main branch. Each time you push a change, GitHub Actions automatically triggers the deployment, pulling the latest version of your code and deploying it to your live site on Kinsta.

You can monitor the status of your deployment by going to the Actions tab in your GitHub repository. If the workflow encounters errors, you’ll see detailed logs to help you troubleshoot and fix the issues.

Summary

By setting up continuous deployment for your WordPress site using GitHub Actions, you automate your development workflow, ensuring that every change pushed to GitHub is automatically deployed to your live site on Kinsta.

It also allows you to integrate additional workflows into the pipeline, such as testing and formatting using the @wordpress/scripts package.

What are your thoughts on this process? Is there something else you’d like us to explain, or have you experienced any errors while following this guide? Please share your questions or feedback in the comment section below!

The post How to continuously deploy your WordPress site to Kinsta with GitHub Actions appeared first on Kinsta®.

]]>
https://kinsta.com/blog/continuous-deployment-wordpress-github-actions/feed/ 0