Creating static websites using WordPress and Astro
9 mins read

Creating static websites using WordPress and Astro

Astro Theme is a modern front-end framework that helps developers quickly and efficiently build static websites. With Astro, developers can leverage the powerful features of modern JavaScript frameworks such as React, Vue.js, and Svelete to create dynamic user interfaces while generating static HTML, CSS, and JavaScript files during the construction process.

When combined with WordPress as a headless content management system (CMS), Astro can achieve seamless integration of backend APIs and front-end code, efficiently developing static websites with dynamic content. This method has several benefits.

Static websites generated using Astro and WordPress backend have excellent performance. They can provide services directly from the Content Delivery Network (CDN) without the need for server-side processing, thereby accelerating loading speed and bringing a smoother user experience.

This tutorial will guide you through using Astro and WordPress backend hosted by static website hosting services to establish a static website.

 

The role of WordPress as a headless content management system

Headless content management systems like WordPress separate content management and delivery layers. It allows the backend to maintain content, while different systems (such as Astro) handle the frontend.

WordPress acts as a content repository, providing data to the front-end, while the front-end displays content to users through APIs. This architecture can reuse content for multiple outputs, thereby improving flexibility and providing WordPress users with a familiar content management experience.

The separation of front-end and back-end also provides greater flexibility for front-end design and content migration. In addition, implementing accessibility through application programming interfaces (APIs) can also protect the future of content.

Set up development environment

You must follow three steps to set up the environment:

  • Install Astro.
  • Establish a WordPress website.
  • Create a WordPress temporary storage environment.

Preconditions

To learn this tutorial, please ensure that you have the following qualifications:

  • Basic understanding of HTML, CSS, and JavaScript
  • Node.js and NPM (Node Package Manager) or Yarn are installed on the computer
  • Kinsta account. Register to host a static website for free and access the MyKinsta dashboard.

Installing Astro

  1. Create a new directory for your project and navigate to it.
  2. Run the following command on the terminal to set up a scaffold for the new project
    npm create astro@latest

    This step will generate configuration prompts. Please make the necessary settings.

    Instructions for configuring new Astro projects.
    Instructions for configuring new Astro projects.
  3. After the project is successfully created, run npm run dev on the http://localhost:4321/ Start the local development server.

    Astro installation successful.
    Astro installation successful.

Establishing a WordPress website

Taking Kinsta as an example, please follow the steps below to create a WordPress website on Kinsta.

  1. Click on WordPress Sites on the MyKinsta panel, then Create a site.
  2. Select the Install WordPress option and click Continue.
  3. Provide the Site name, select the data center location, and then click Continue.
  4. Provide all other information and click Continue.
  5. After the website is created, you should see the message “Your site has been created!”.

Create a WordPress temporary storage environment

Each WordPress installed in Kinsta can choose to create a free staging environment independent of the actual production website. This is very suitable for testing new WordPress versions, plugins, code, and general development work.

The steps to create a WordPress temporary storage environment on Kinsta are as follows.

  1. Click “Live” on the menu bar, then click “Create New Environment”.

    WordPress temporary storage environment.
    WordPress temporary storage environment.
  2. Select Standard environment and click Continue.
  3. Click “Clone an existing environment”, provide the environment name, select “Live” for the environment you want to clone, and then click “Continue”.
  4. After deployment, you can find the WordPress temporary storage environment on the “Live” menu.

    Successfully created temporary environment.
    Successfully created temporary environment.

 

Integrating WordPress with Astro

There are two main methods to integrate WordPress with Astro: REST API and GraphQL. This guide uses the GraphQL method.

To integrate WordPress with Astro, you must:

  • Install WPGraphQL.
  • Connect Astro to WordPress.

Install WPGraphQL

Firstly, install the WPGraphQL plugin on the WordPress website, and then use GraphQL to connect Astro to the website.

  1. On the MyKinsta dashboard, select your WordPress website.
  2. Click “Staging” on the menu bar, then click on the top right corner to open the WP management backend

    Website information page.
    Website information page.
  3. Provide credentials for creating WordPress websites.
  4. Click on the Plugins menu on the left navigation bar.
  5. Click “Add New Plugin” to add the WPGraphQL plugin.
  6. Search for “WPGraphQL”, click “Install New” to install the WPGraphQL plugin, and then click “Activate”.

    Install the WPGraphQL plugin.
    Install the WPGraphQL plugin.
  7. To test whether the installed WPGraphQL plugin runs as expected, open the GraphQL menu on the navigation bar and click on the GraphQL IDE.
  8. Use the following code in the GraphiQL IDE, and then click “Run” in the upper left corner to execute the GraphQL query:
    {
    posts {
    nodes {
    slug
    excerpt
    title
    }
    }
    }

    This GraphQL query can effectively retrieve slugs, excerpts and titlesof articles on the WordPress website.

  9. Run GraphQL queries.
    Run GraphQL queries.

    On the left side of the GraphQL IDE, you can see the list of posts returned by running the GraphQL query. Your WordPress GraphQL endpoint can be accessed through https://your_wordpress_staging_url/graphql Access.

Note: Ensure that the WordPress website is pushed from the staging environment to the real-time environment after completing all tests and being satisfied with the website’s performance and functionality.

Connect Astro to WordPress

To connect Astro to WordPress, follow the instructions below:

  1. Create a folder called graphql in the src folder of the Astro project.
  2. Create a wordPressQuery. ts file in the graphql folder.
  3. Use the following code in the wordPressQuery. ts file. Ensure that the https://your_wordpress_staging_url/graphql Replace with your WordPress temporary URL.
    interface gqlParams {
    query: String;
    variables?: object;
    }
    export async function wpquery({ query, variables = {} }: gqlParams) {
    const res = await fetch('https://your_wordpress_staging_url/graphql', {
    method: "post",
    headers: {
    "Content-Type": "application/json",
    },
    body: JSON.stringify({
    query,
    variables,
    }),
    });
    if (!res.ok) {
    console.error(res);
    return {};
    }
    const { data } = await res.json();
    return data;
    }

    This code defines an interface gqlParams and an asynchronous function wpquery to facilitate GraphQL queries on WordPress websites.

Developing websites using Astro and WordPress

  1. To create a new static page in Astro, create a file called blog.astro in the src/pages directory.
  2. Paste the following code into the newly created file:
    ---
    import Layout from "../layouts/Layout.astro";
    import { wpquery } from "../graphql/wordPressQuery";
    const data = await wpquery({
    query: `
    {
    posts{
    nodes{
    slug
    excerpt
    title
    }
    }
    }  
    `,
    });
    ---
    <Layout title="Astro-WordPress Blog Posts">
    <main>
    <h1><span class="text-gradient">Blog Posts</span></h1>
    {
    data.posts.nodes.map((post: any) => (
    <>
    <h2 set:html={post.title} />
    <p set:html={post.excerpt} />
    </>
    ))
    }
    </main>
    </Layout>
    <style>
    main {
    margin: auto;
    padding: 1rem;
    width: 800px;
    max-width: calc(100% - 2rem);
    color: white;
    font-size: 20px;
    line-height: 1.6;
    }
    h1 {
    font-size: 4rem;
    font-weight: 700;
    line-height: 1;
    text-align: center;
    margin-bottom: 1em;
    }
    </style>

    This code demonstrates how to use the wpquery function to retrieve data from the WordPress website using GraphQL and present it on the Astro website.

  3. Start the local development server using npm run dev and view the latest WordPress blog articles on the Astro website at http://localhost:4321/blog .

    The Astro project displays WordPress articles.
    The Astro project displays WordPress articles.

To handle the dynamic routing of individual blog posts, you need to combine Astro’s dynamic routing with WordPress GraphQL’s query variables. By using the article ID or title as query variables, you can dynamically generate the page content for each blog article. In this way, you can get a more personalized user experience on the website.

Deploying static websites on Kinsta

Now, push the code to your favorite Git provider (Bitbucket, GitHub, or GitLab). Then, follow the following steps to deploy the static website to Kinsta:

  1. In the MyKinsta panel, click on Static Sites and then Add site.
  2. Authorize Kinsta with Git provider.
  3. Select a GitHub repository and a Default branch. Provide the Display name for the static website and select the “Automatic deployment on the commit” box. This will automatically deploy all new changes made to the version library. Click Continue.
  4. In the “Build settings” section, Kinsta will automatically complete all fields. Keep it as is, then click Create Site.
  5. Visit the Astro website by accessing the URL displayed as a domain on the “Overview” page of the deployed website. You can access it by https://your_kinsta_site_url/blog Access blog posts.

 

Summary

You can do more with Astro and WordPress. The WordPress API can be used to access various data on websites and create unique use cases together with Astro.

What is your opinion on Headless WordPress and Astro? Have you explored their potential in creating unique solutions? Please share your experience in the comments section below.