WPSurfer.com

GitHub and WordPress Static Sites

Published on November 13, 2024 | Updated on November 14, 2024

I used to create and manage WordPress sites using Cloudways.

Then I got tired of using Cloudways as it keeps introducing features that I don’t need and that you have little control over.

So I deployed a Digital Ocean server using the CloudPanel Solution from the MarketPlace.

The intention was to move my WordPress websites into that server but I figured how to create static sites with it.

I moved my sites on Cloudways to local instances created with Local by Flywheel and then created three Python Scripts to push the changes to my Digital Ocean Server.

  1. A script to create the static version of the site.
  2. A second script that uses RSync to push the changes to my server
  3. Another simple script to clear Cloudflare Full Page Caching.

I got pretty happy with it, then I thought that If I figured how to work with GitHub, I could push my local files to CloudFlare pages and not to a server.

I stopped paying hosting fees, which was not main reason for doing this since Digital Ocean was just six dollars a month.

This is how I did it.

Let’s get started



What’s Git and GitHub?

Git is a distributed version control system that allows multiple people to work on the same project simultaneously without overwriting each other’s work.

Git helps track changes in the source code, manage different versions of files, and collaborate on projects.

Git operates on your local machine and can also be integrated with services like GitHub, GitLab, Bitbucket, etc.

GitHub is a cloud-based platform that hosts Git repositories online

So if you want to create a workflows to work locally and push changes straight to server pages:

  1. You should know git commands
  2. Have a GitHub account and a public or private repository.

Since GitHub is pretty popular, you will see that services like CloudFlare Pages integrate well with them.


Creating a GitHub Account and Private Repo

First and Foremost, you should create a GitHub account and create a private repository.

You can create a public one but why would you do such a thing?

You can always change from public to private in the visibility settings if you change your mind.

Since the intention is to host static sites that are meant to be public, you don’t need to worry about that aspect that much.

Your repository can be named anything you want and you can even name it after your domain name.


Create an SSH Key

If you want to be able to make changes to your repository, you need to create SSH keys.

SSH keys are a way to securely connect to a computer or server over the internet without using a username or password.

Here’s how it works in simple terms:

  • Private Key: This is your secret key. You keep it safe on your computer.
  • Public Key: This is the matching key that you can share with others, like a lock that you put on a door.

To create SSH keys you need to open the terminal and type this command

ssh-keygen -t ed25519 -C "yourmail@mail.com"
  • ssh-keygen: This is the command used to generate a new SSH key pair (a public key and a private key).
  • -t ed25519: This specifies the type of encryption for the key. In this case, ed25519 is a modern, secure encryption method used for generating the key pair. It’s considered faster and more secure than the older rsa method.
  • -C “yourmail@mail.com”: This is an optional comment that you can add to your key. It’s often used to label or identify the key. In this case, it’s identifying the key as being for “yourmail@mail.com”. This helps you recognize what the key is used for, especially if you have multiple keys on your computer.

When prompted to write a passphrase, you can write one or leave it blank.

Add your public key to your GitHub account by going to your GitHub Profile >> SSH keys and add New SSH Key.

From that moment on, you can connect to your GitHub repositories.

You can test if it’s working by running the following command in your terminal:

ssh -T git@github.com

If the key is correctly set up, you’ll see a message like this:

Hi  username! You've successfully authenticated, but GitHub does not provide shell access.

If there’s an issue, you might get an error like this:

Permission denied (publickey).

Create a Local Folder and a Static Files

Now that you have active connection with your GitHub Repo

You have to create a folder for your website or websites.

I have a folder called GitHub on my desktop and inside of it, I have a folder called wpsurfer.com

So when I want to work on such folder, I go to the terminal and type or paste this command:

cd ~/Desktop/github/wpsurfer.com

You can use plugins like Simply Static or Staatic or you can create a Python script that create a static version of your site for you.

Once you have the files, place them on the folder created in the previous step.


Sync your Local Repo with GitHub Repo

So if I want to sync my local repository with my GitHub repository, first I need to the folder I want to sync.

in my case, I will type or copy and paste this into my terminal:

cd ~/Desktop/github/wpsurfer.com

If your local folder isn’t already a Git repository, you need to initialize it. Use the following command for that,

git init

if you are wondering what the command does, this creates the necessary files and directory structure to track your project’s history, allowing you to start version control.

If you have enabled “hidden files” on your computer, you will see a “.git” folder on the root folder.


Now you have to run this command, replace “git@github.com:ticolibre/wpsurfer.git” with the SSH values provided on your GitHub Repo.

This command links your local repository to the remote repository on GitHub.

git remote add origin git@github.com:ticolibre/wpsurfer.com.git

To make sure that the process worked, run this command and you will get some values followed by (fetch) and (push)

git remote -v

If you have any local changes (new files, modified files, etc.) that you want to push to GitHub, you’ll first need to stage them. Use:

git add .

You will not see any visible output by default, unless there is an error.


After staging your changes, commit them with a message describing what you’ve done. For example:

git commit -m "Initial commit"

Now, you can push the changes to your GitHub repository using the git push command:

git push -u origin master

Can the Process be Automated?

The process can be automated from the start but I don’t think that automating the whole process is a good investment of your time when you have a handful of sites.

I followed four steps described in the previous section to push subsequent commits so if you want to create a script, you should only focus on these four:

When it comes to updates and subsequent commits, you want to focus on being on the right folder:

cd ~/Desktop/github/wpsurfer.com

Then you have to stage them.

git add .

Then you want to add a descriptive name that helps you identify when an update was pushed to GitHub.

git commit -m "Initial commit"


And then a prompt that detects the name of the branch and push the commit.

git push -u origin master

Keep in mind that this won’t find any issues if you are working locally and you just want GitHub for version control and the repo to be integrated with a service such as CloudFlare Pages.

If you make changes to your online repository, but you would have to consider that when you build a script.


Python Script to Push Commits

In case you don’t want to do you homework, you might want to use this Python Script or modify it.

The list of directories have been hard-coded and that’s probably all you have to change to make it work.

import os
import subprocess
from datetime import datetime
# List of directories to choose from
directories = [
    "~/Desktop/github/wpsurfer.com",
    "~/Desktop/github/wpsurfer.co.cr",
]
# Expand user directories (handle ~)
directories = [os.path.expanduser(d) for d in directories]
def select_directory():
    print("Select a directory to sync with GitHub:")
    for idx, dir in enumerate(directories, 1):
        print(f"{idx}. {dir}")
    try:
        choice = int(input("Enter the number of the directory you want to select: "))
        if 1 <= choice <= len(directories):
            return directories[choice - 1]
        else:
            print("Invalid choice.")
            return select_directory()
    except ValueError:
        print("Please enter a valid number.")
        return select_directory()
def run_git_commands(directory):
    # Change working directory to selected directory
    os.chdir(directory)
    # Perform git add .
    print("Running 'git add .' ...")
    subprocess.run(["git", "add", "."], check=True)
    # Check if there are any changes to commit
    result = subprocess.run(["git", "status", "--porcelain"], capture_output=True, text=True)
    if result.stdout.strip():
        # There are changes, so commit them
        today = datetime.today().strftime('%Y-%m-%d')
        current_time = datetime.today().strftime('%H-%M')
        commit_message = f"{os.path.basename(directory)} {today} {current_time}"
        print(f"Running 'git commit -m \"{commit_message}\"' ...")
        subprocess.run(["git", "commit", "-m", commit_message], check=True)
    else:
        print("No changes to commit. Working tree is clean. Skipping commit.")
    # Automatically get the current branch
    result = subprocess.run(["git", "rev-parse", "--abbrev-ref", "HEAD"], capture_output=True, text=True)
    branch = result.stdout.strip()
    print(f"Detected branch: {branch}")
    # Push to the current branch
    print(f"Running 'git push -u origin {branch}' ...")
    subprocess.run(["git", "push", "-u", "origin", branch], check=True)
def main():
    # Select the directory
    selected_directory = select_directory()
    # Run the git commands
    run_git_commands(selected_directory)
if __name__ == "__main__":
    main()

I run these using Visual Studio Code

I tested these a few times and it does the job as expected.

I am not a coder so you can definitely find some rooms for improvement in that code.


Where to Host your Static Sites?

Now that you have your static sites on a GitHub Repo, you need to link a hosting service to it.

Consider these options for your static websites:

  • CloudFlare Pages has a 100% free tier, no need to think about Bandwidth and limits.
  • Netlify has a free tier with 100GB Bandwidth and integrates well with GitHub.
  • Kinsta also provides a free tier that includes 100GB of bandwidth.
  • Sevalla also offers 100GB of bandwidth a month

If you don’t want to rely on free services and GitHub, you can create static websites and have control over everything by using CloudPanel.

CloudPanel: Hosting Control Panel Review

CloudPanel: Hosting Control Panel Review

This post is the result of testing CloudPanel on Digital Ocean and consider as a the future for hosting my WordPress sites


Current Workflow

I am using CloudFlare Pages since Nov, 2024 and the whole process has been quick and easy.

  1. Local Folders with Static Sites are already linked With GitHub Repositories.
  2. I start my local WordPress sites using Docker.
  3. Once I am done working on a site, I run a single script that (1) that creates a static version of my site (2) remove old site from my local repo retaining .git folder and .gitignore file. (3) push the new commit to my Github Repository and these changes are pushed to CloudFlare.

Keep this in Mind

Regardless of the method that you use to generate a static WordPress website, don’t delete these from your Local Repository:

#1.gitFolder
#2.gitignoreFile

These files are hidden, the first ones contains the configuration and keeps track of everything.

The second one if you set it up will ignore files that you don’t want to push to your GitHub Repo


Final Thoughts

By the way, you can try using GitHub Desktop if you don’t want to complicate your life with Git and Python.

And there might be an easier route instead of my current workflow that I might not know of.

I wanted to learn something new and I definitely did.


Manuel Campos

Manuel Campos

I am José Manuel. I am writing about things I know and things that I am learning about WordPress. I hope you find the content of this blog useful.