One place for hosting & domains

      How To Use WP-CLI v2 to Manage Your WordPress Site from the Command Line


      The author selected the Free Software Foundation to receive a donation as part of the Write for DOnations program.

      Introduction

      WP-CLI is a command-line tool for WordPress development and administrative tasks. It provides several commands that you can use to manage your WordPress website without needing to log in to the dashboard and navigate through the pages.

      Using WP-CLI to manage your WordPress installation over the conventional interface process helps to speed up your workflow. For many aspects of your website, you can also use WP-CLI in Bash scripts to automate tasks that are tedious or take a long time to perform.

      In this tutorial, you’ll use many of the features of WP-CLI and discover how it can fit into your workflow. You’ll cover common operations such as managing plugins and themes, creating content, working with the database, and updating WordPress. The capabilities of WP-CLI go beyond this tutorial; however, you’ll be able to transfer the skills from this tutorial to work with the more common options of other WP-CLI features.

      Prerequisites

      To follow this tutorial, you’ll need a secure WordPress installation. If you need to set up WordPress, you can follow these tutorials for your chosen server distribution:

      Note: It’s also possible to install WordPress with WP-CLI if you don’t have an existing setup, but we won’t be covering that aspect in this article.

      Step 1 — Installing WP-CLI

      In this step, you’ll install the latest version of the WP-CLI tool on your server. The tool is packaged in a Phar file, which is a packaging format for PHP applications that makes app deployment and distribution convenient.

      You can download the Phar file for WP-CLI through curl:

      • curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar

      Once you have downloaded the file, run the following command to verify that it is working:

      You will receive the following output:

      Output

      OS: Linux 5.4.0-51-generic #56-Ubuntu SMP Mon Oct 5 14:28:49 UTC 2020 x86_64 Shell: /bin/bash PHP binary: /usr/bin/php7.4 PHP version: 7.4.3 php.ini used: /etc/php/7.4/cli/php.ini WP-CLI root dir: phar://wp-cli.phar/vendor/wp-cli/wp-cli WP-CLI vendor dir: phar://wp-cli.phar/vendor WP_CLI phar path: /home/ayo WP-CLI packages dir: WP-CLI global config: WP-CLI project config: WP-CLI version: 2.4.0

      Next, make the file executable with the following command:

      At this point, you can execute the wp-cli.phar file directly to access the WP-CLI tool. To make it available globally on the system, move it to your /usr/local/bin/ directory and rename it to wp. This ensures that you can access WP-CLI from any directory by entering the wp command at the start of a prompt:

      • sudo mv wp-cli.phar /usr/local/bin/wp

      Now, you will be able to issue the following command to check the installed version of WP-CLI:

      Output

      WP-CLI 2.4.0

      In this step, you installed WP-CLI on your server. You can check out alternative installation methods in the documentation. In subsequent sections, you’ll explore the tasks you can accomplish through the WP-CLI interface.

      Step 2 — Configuring WordPress Plugins

      It can be tedious to install and manage WordPress plugins through the admin user interface. It’s possible to offload such tasks to WP-CLI to make the process much faster. In this section you will learn to install, update, and delete plugins on a WordPress site through the command line.

      Before you proceed, make sure you are in the directory of your WordPress installation:

      Remember to change the highlighted directory name to the directory that contains your WordPress installation. This might be your domain name, if you followed the prerequisite tutorials.

      Listing Current Plugins

      You can list the currently installed plugins on a WordPress site with the following command:

      It displays a list of plugin names along with their status, version, and an indication of an available update.

      Output

      +---------+----------+-----------+---------+ | name | status | update | version | +---------+----------+-----------+---------+ | akismet | inactive | available | 4.1.7 | | hello | inactive | none | 1.7.2 | +---------+----------+-----------+---------+

      Searching for Plugins

      You can search for plugins through the search bar on the WordPress plugin repository page or you can use the following command for quicker access:

      Once you run this command, you will receive a list of the top 10 plugins that match the search term (as of early 2021). The expected output for the seo query is:

      Output

      Success: Showing 10 of 4278 plugins. +------------------------------------------------------------+---------------------+--------+ | name | slug | rating | +------------------------------------------------------------+---------------------+--------+ | Yoast SEO | wordpress-seo | 98 | | All in One SEO | all-in-one-seo-pack | 92 | | Rank Math – SEO Plugin for WordPress | seo-by-rank-math | 98 | | The SEO Framework | autodescription | 98 | | SEOPress, on-site SEO | wp-seopress | 98 | | Slim SEO – Fast & Automated WordPress SEO Plugin | slim-seo | 92 | | W3 Total Cache | w3-total-cache | 88 | | LiteSpeed Cache | litespeed-cache | 98 | | SEO 2021 by Squirrly (Smart Strategy) | squirrly-seo | 92 | | WP-Optimize – Clean, Compress, Cache. | wp-optimize | 96 | +------------------------------------------------------------+---------------------+--------+

      You can go to the next page by using the --page flag:

      • wp plugin search seo --page=2

      Take note of the value in the slug column. You’ll use this value to install or update the plugin on the command line.

      Installing Plugins

      You can install one or more plugins by using the wp plugin install command. You find the name of the plugin you want to install (in the slug column) and pass it as an argument to wp plugin install. You can also find the name of the plugin in the URL of the plugin page.

      Plugin name in URL

      • wp plugin install jetpack wordpress-seo gutenberg

      The output indicates the progress and completion of the installation of each of the plugins:

      Output

      Installing Jetpack – WP Security, Backup, Speed, & Growth (9.3.1) Downloading installation package from https://downloads.wordpress.org/plugin/jetpack.9.3.1.zip... Unpacking the package... Installing the plugin... Plugin installed successfully. Installing Yoast SEO (15.6.2) Downloading installation package from https://downloads.wordpress.org/plugin/wordpress-seo.15.6.2.zip... Unpacking the package... Installing the plugin... Plugin installed successfully. Installing Gutenberg (9.8.1) Downloading installation package from https://downloads.wordpress.org/plugin/gutenberg.9.8.1.zip... Unpacking the package... Installing the plugin... Plugin installed successfully. Success: Installed 3 of 3 plugins.

      You can run the wp plugin list command again to confirm that you’ve installed the plugins successfully:

      Output

      +---------------+----------+-----------+---------+ | name | status | update | version | +---------------+----------+-----------+---------+ | akismet | inactive | available | 4.1.7 | | gutenberg | inactive | none | 9.8.1 | | hello | inactive | none | 1.7.2 | | jetpack | inactive | none | 9.3.1 | | wordpress-seo | inactive | none | 15.6.2 | +---------------+----------+-----------+---------+

      If you want to install a plugin from a remote source other than the WordPress plugin repository, you can pass the zip file’s URL as an argument to wp plugin install. This can be helpful for installing custom or premium plugins. For example, the following command will install the myplugin.zip file hosted on example.com. Make sure to replace the highlighted URL with a link to the plugin zip file before running the command:

      • wp plugin install https://example.com/wp-content/uploads/myplugin.zip

      To install an older version of a plugin in the WordPress repository, specify the desired plugin version through the --version flag:

      • wp plugin install jetpack --version=8.0

      Activating and Deactivating Plugins

      You can install and activate plugins in one go by appending the --activate flag to wp plugin install:

      • wp plugin install redirection --activate

      Output

      Installing Redirection (5.0) Downloading installation package from https://downloads.wordpress.org/plugin/redirection.zip... Using cached file '/home/ayo/.wp-cli/cache/plugin/redirection-5.0.zip'... Unpacking the package... Installing the plugin... Plugin installed successfully. Activating 'redirection'... Warning: Plugin 'redirection' is already active. Success: Installed 1 of 1 plugins.

      To activate or deactivate one or more plugins, use the wp plugin activate and wp plugin deactivate commands respectively:

      • wp plugin activate jetpack gutenberg
      • wp plugin deactivate jetpack gutenberg

      Or you can use the --all flag to activate or deactivate all plugins at once. This is useful if you want to debug a problem in your WordPress installation:

      • wp plugin activate --all
      • wp plugin deactivate --all

      Updating Plugins

      You can update plugins through the wp plugin update command. You can choose to update a set of plugins or all of them at once by appending the --all flag. For example, to update the akismet plugin, you can run the following command:

      You would receive output similar to:

      Output

      Enabling Maintenance mode... Downloading update from https://downloads.wordpress.org/plugin/akismet.4.1.8.zip... Unpacking the update... Installing the latest version... Removing the old version of the plugin... Plugin updated successfully. Disabling Maintenance mode... +---------+-------------+-------------+---------+ | name | old_version | new_version | status | +---------+-------------+-------------+---------+ | akismet | 4.1.7 | 4.1.8 | Updated | +---------+-------------+-------------+---------+ Success: Updated 1 of 1 plugins.

      Deleting plugins

      To delete WordPress plugins, you can use the wp plugin delete command. You can specify one or more plugins to delete like the following:

      • wp plugin delete redirection

      Your output will confirm the deletion:

      Output

      Deleted 'redirection' plugin. Success: Deleted 1 of 1 plugins.

      You can also delete all the installed plugins in one go by appending the --all flag instead of specifying the plugin names one after the other:

      In this step, you’ve used WP-CLI to manage the plugins on your WordPress website. It’s much faster to perform actions compared to clicking through the admin dashboard. In the next section, you’ll leverage WP-CLI for installing and managing WordPress themes.

      Step 3 — Configuring Themes

      The process of managing themes through WP-CLI is almost identical to the way you can use it to manage plugins. In this section, you’ll source and apply new themes to a WordPress website through the wp theme subcommand.

      First, check what themes you currently have installed on the website:

      You’ll receive a list of the installed themes:

      Output

      +-----------------+----------+-----------+---------+ | name | status | update | version | +-----------------+----------+-----------+---------+ | twentynineteen | inactive | available | 1.8 | | twentytwenty | inactive | none | 1.6 | | twentytwentyone | active | available | 1.0 | +-----------------+----------+-----------+---------+

      There are three themes currently installed and the active one is twentytwentyone. If you want to find something with more features, you can try a search like the following:

      The output shows there are 832 themes that match the color search term:

      Output

      Success: Showing 10 of 832 themes. +---------------------+---------------------+--------+ | name | slug | rating | +---------------------+---------------------+--------+ | Color | color | 0 | | All Colors | all-colors | 100 | | Color Blog | color-blog | 98 | | Color Block | color-block | 0 | | X Blog color | x-blog-color | 0 | | Multicolor Business | multicolor-business | 0 | | ColorNews | colornews | 100 | | Colorist | colorist | 100 | | ColorMag | colormag | 98 | | MultiColors | multicolors | 74 | +---------------------+---------------------+--------+

      You can page through the results using the --page flag. For this example, just go ahead and install the ColorMag theme since it has a pretty good rating. The --activate flag activates the theme immediately:

      • wp theme install colormag --activate

      The output will confirm the installation:

      Output

      Installing ColorMag (2.0.4) Downloading installation package from https://downloads.wordpress.org/theme/colormag.2.0.4.zip... Unpacking the package... Installing the theme... Theme installed successfully. Activating 'colormag'... Success: Switched to 'ColorMag' theme. Success: Installed 1 of 1 themes.

      If you visit your website, you’ll find that the ColorMag theme was applied successfully.

      ColorMag theme

      The output from the wp theme list command notes that there is an update available for both the twentynineteen and twentytwentyone themes. You can update them both using the following command:

      You’ll receive output similar to the following:

      Output

      Downloading update from https://downloads.wordpress.org/theme/twentynineteen.1.9.zip... Unpacking the update... Installing the latest version... Removing the old version of the theme... Theme updated successfully. Downloading update from https://downloads.wordpress.org/theme/twentytwentyone.1.1.zip... Unpacking the update... Installing the latest version... Removing the old version of the theme... Theme updated successfully. +-----------------+-------------+-------------+---------+ | name | old_version | new_version | status | +-----------------+-------------+-------------+---------+ | twentynineteen | 1.8 | 1.9 | Updated | | twentytwentyone | 1.0 | 1.1 | Updated | +-----------------+-------------+-------------+---------+ Success: Updated 2 of 2 themes.

      The wp theme command offers many subcommands that can help you achieve tasks like getting the details of a theme, checking if a particular theme is installed, or even deleting one or more themes. You can explore all of the options by prepending help before the subcommand, as in wp help theme or wp help theme install.

      Now that you can manage themes through WP-CLI, you’ll review the options that the tool provides for managing WordPress content.

      Step 4 — Creating Posts and Pages

      WP-CLI provides several ways to manage content through the command line. It can be more comfortable to write posts in the terminal if you’re familiar with a command-line editor like nano or vim.

      You can browse the list of posts on the site with:

      You’ll receive a list of posts:

      Output

      +----+--------------+-------------+---------------------+-------------+ | ID | post_title | post_name | post_date | post_status | +----+--------------+-------------+---------------------+-------------+ | 1 | Hello world! | hello-world | 2021-01-24 12:32:06 | publish | +----+--------------+-------------+---------------------+-------------+

      The output shows one published post with the title of Hello world! and an ID of 1. To delete this post, use the wp post delete command and pass it the post ID:

      Your output will confirm the post’s deletion:

      Output

      Success: Trashed post 1.

      To create a new post, run the following command:

      • wp post create --post_status=publish --post_title="Sample post created with WP-CLI" --edit

      This command uses the --post_status flag to set the status of the post. Setting it to publish ensures that the post is published immediately after running the command. If you want to create a draft instead, set the --post_status flag to draft. The --post_title flag is how you can specify the title of the post, while --edit causes the post body to be opened in the default system editor (vim). You can find out the other flags that you can use in conjunction with the create subcommand by typing wp help post create in your terminal.

      Once the vim editor is open, press the i key to enter INSERT mode then enter the content of the post into the editor. Once you’re done editing the post, exit the vim editor by pressing the ESC button then type :wq and press ENTER. You will receive the following output after exiting vim:

      Output

      Success: Created post 6.

      If you enter the wp post list command again, you will find the post you just created. You can also check the frontend of the website.

      WP-CLI post

      Instead of writing the post on the command line, it’s also possible to import the post content from a text file. First, you need to create the file. For example:

      Next, open the file in a command-line editor to add or edit your content:

      Once you’re through with the edits, save and close the file by pressing CTRL-X followed by Y to save. You can import the contents of that file as a WordPress post by using the following command. All you need to do is specify the path to the file after the create subcommand. For the example file here, you would run:

      • wp post create ./content.txt --post_title="Sample Post Created with WP-CLI" --post_status=publish

      If you want to create a page instead of a post, append the --post_type flag and set it to page:

      • wp post create --post_title="A simple page" --post_status=draft --post_type=page

      Generating Posts or Pages

      WP-CLI also provides an option to cleanly generate posts and pages with dummy data. This is useful if you need custom data to quickly test a theme or plugin that you are developing. The following command is to generate posts. If you don’t include additional flags, it will generate 100 posts by default.

      You can change the number of posts generated by using the --count flag:

      • wp post generate --count=20

      If you want to generate pages instead of posts, append the --post_type flag and set it to page:

      • wp post generate --count=20 --post_type=page

      You can also use the wp help post generate to see other available options that can help you get your desired result.

      WordPress Revisions

      It is not uncommon for older sites to have tens or hundreds of revisions on their main pages due to years of editing and updating content. Revisions can be helpful in case you need to revert back to a previous version of your content, but they can also hurt the performance if there are too many. You can clean up all the post revisions in the WordPress database by executing the following command:

      • wp post delete $(wp post list --post_type="revision" --format=ids) --force

      The command enclosed in the parenthesis is evaluated first and it will produce the ids of all the post revisions that are present passing them to the delete subcommand. The --force flag is necessary because posts of type 'revision' do not support being sent to trash.

      Step 5 — Managing Your Database

      One of the most useful features of WP-CLI is its ability to interact with the MySQL database. For example, if you need an interactive session, you can enter a MySQL prompt with the following command:

      You can then use the MySQL shell as you normally would and, once you are through with your tasks, exit the shell by typing exit.

      For one-off queries, you can use the wp db query command by passing a valid SQL query as an argument to the command. For example, to list all the registered users in the WordPress database, you could run:

      • wp db query "SELECT user_login,ID FROM wp_users;"

      You will be presented with an output similar to the following:

      Output

      +------------+----+ | user_login | ID | +------------+----+ | admin | 1 | +------------+----+

      With wp db query you can run any one-off SQL query for the WordPress database.

      Backing Up and Restoring

      WP-CLI also allows you to back up your WordPress database. Running this following command will place a SQL dump file in the current directory. This file contains your entire WordPress database including your posts, pages, user accounts, menus, and so on:

      Once the file is produced, you can move it to a different location for safekeeping:

      Output

      Success: Exported to 'wordpress-2021-01-25-25618e7.sql'.

      You can also import a SQL dump file into your database through the wp db import command. This is useful when you are migrating a WordPress website from one location to another.

      Searching and Replacing

      Another common operation you can perform with WP-CLI is a find-and-replace operation. You can make a dry run first to find out how many instances it would modify. The first string is the search component while the second is the replacement:

      • wp search-replace --dry-run 'example.com' 'example.net'

      After running this, your output would be similar to the following:

      Output

      Success: 10 replacements to be made.

      Once you are sure you want to proceed, remove the --dry-run flag from the previous command:

      • wp search-replace 'example.com' 'example.net'

      In this step, you’ve reviewed several database operations that you can perform using WP-CLI. You can also complete other operations, such as optimizing the database, viewing database tables, deleting a database, or resetting one. You can explore the other options under the wp db subcommand by typing wp help db in your terminal.

      Step 6 — Updating WordPress

      You can update the core WordPress file with WP-CLI. You can examine the current version of WordPress that you have installed by running:

      Output

      5.6

      You can check for updates through the wp core check-update command. If your version is not the latest, this will produce an output similar to the following:

      Output

      +---------+-------------+-----------------------------------------------------------------------+ | version | update_type | package_url | +---------+-------------+-----------------------------------------------------------------------+ | 5.6.1 | minor | https://downloads.wordpress.org/release/wordpress-5.6.1-partial-0.zip | +---------+-------------+-----------------------------------------------------------------------+

      If an update is available, you can install it with:

      Output

      Updating to version 5.6.1 (en_US)... PHP Warning: Declaration of WP_CLICoreCoreUpgrader::download_package($package, $check_signatures = true) should be compatible with WP_Upgrader::download_package($package, $check_signatures = false, $hook_extra = Array) in phar:///usr/local/bin/wp/vendor/wp-cli/core-command/src/WP_CLI/Core/CoreUpgrader.php on line 30 Warning: Declaration of WP_CLICoreCoreUpgrader::download_package($package, $check_signatures = true) should be compatible with WP_Upgrader::download_package($package, $check_signatures = false, $hook_extra = Array) in phar:///usr/local/bin/wp/vendor/wp-cli/core-command/src/WP_CLI/Core/CoreUpgrader.php on line 30 Downloading update from https://downloads.wordpress.org/release/wordpress-5.6.1-partial-0.zip... Unpacking the update... Success: WordPress updated successfully.

      You can also update to a specific version by setting the --version flag to the version number. If you want to revert to an older version, you also need to add the --force flag, but this isn’t recommended:

      • wp core update --version=5.6
      • wp core update --version=5.0 --force

      In this final step, you updated your version of WordPress with WP-CLI.

      Conclusion

      For WordPress developers and adminstrator’s working on the command line, WP-CLI is a great addition to the toolbox. In this tutorial, we covered several of the more common tasks that you can perform through the command line.

      WP-CLI has many more commands and options that you can familiarize yourself with to achieve even more on the command line without the web interface. Use wp help <command> to find out all the things you can do with a specific subcommand. There are also many community tools that extend WP-CLI with even more features.

      For more tutorials on WordPress, check out our WordPress topic page.



      Source link

      All the Ways to Generate a Next.js Site


      How to Join

      This Tech Talk is free and open to everyone. Register on Eventbrite here to receive a link to join on Wednesday, January 27, 2021, 11:30 a.m.–12:30 p.m. ET.

      About the Talk

      Next.js is an amazing tool that lets us build sites quickly. It handles things like routing, lazy loading, and image optimization. Learn how Next.js allows us to build the fastest possible site.

      What You’ll Learn

      • How Next.js features help us build the fastest possible blogs, websites, and applications
      • Using Incremental Static Generation to update static content after you have built your site
      • Grabbing data from an API

      This Talk is Designed For

      React developers that are looking to streamline your workflow.

      About the Presenter

      Chris Sev is a Senior Developer Advocate at DigitalOcean and the founder of scotch.io. He builds fullstack apps with JavaScript and puts a focus on building businesses.

      To join the live Tech Talk, register here.



      Source link

      How To Build and Deploy a Hugo Site to DigitalOcean App Platform


      Hugo is a static site generator and framework for building websites. With Hugo, you define your themes using HTML and build your content using Markdown or other text processors. Hugo generates HTML that you can host anywhere.

      In this tutorial, you’ll use Hugo to build a small static website and deploy the site to DigitalOcean’s App Platform by using GitHub. Then you’ll make changes to your site and see those changes deployed automatically.

      Prerequisites

      To complete this tutorial, you’ll need:

      Step 1 — Installing Hugo

      To build your Hugo site, you’ll install the hugo command-line tool on your local machine. You’ll use this tool to generate your site, create content pages, and launch a small server you’ll use to test your site before you deploy it.

      Hugo is available as a single binary, so the installation process involves downloading the file to your machine and placing it on your path.

      Download Hugo from the releases page on GitHub. Hugo comes in two versions: the regular version and the extended version. Download the extended version so you have support for asset management and support for CSS preprocessing. Save the file to your Downloads directory.

      Once you’ve downloaded the file, you’ll need to uncompress the file and place it somewhere on your system PATH so you can run the file from any directory.

      On Windows, create the directory C:Hugo, unzip the file you’ve downloaded, and place it in C:hugo. Then add that folder to your PATH environment variable. To do this, use Windows Search and type “environment”. Select Edit Environment Variables for My Account. On the screen that appears, press the Environment Variables button, locate PATH in the System Variables section, and press the Edit button. Add c:hugobin in the text area and press OK to save the settings. Press OK on the rest of the dialogs to close them.

      On macOS or Linux, copy the executable to /usr/local/bin, as this is already included in your PATH environment variable by default.

      First, switch to the Downloads directory:

      Uncompress the file:

      • tar zxvf hugo_extended_0.75.1*.gz

      Then move the file to /usr/local/bin:

      Ensure that Hugo is configured by switching to your home directory and typing the hugo command:

      You’ll see the version number printed to the screen:

      Output

      Hugo Static Site Generator v0.75.1-A4A7BAB7/extended darwin/amd64 BuildDate: 2020-09-15T06:54:33Z

      Now that Hugo is installed, you can create your site.

      Step 2 — Creating the Hugo Project

      Let’s create a small site about sharks. We’ll call it “Sharkopedia”, and it will have pages about different kinds of sharks.

      To create a site, use the hugo new site command. From your home directory, execute the following command:

      • hugo new site sharkopedia

      This creates the directory sharkopedia and displays a welcome message that tells you how to install a theme for your site:

      Output

      Congratulations! Your new Hugo site is created in /Users/your_username/sharkopedia. Just a few more steps and you're ready to go: 1. Download a theme into the same-named folder. Choose a theme from https://themes.gohugo.io/ or create your own with the "hugo new theme <THEMENAME>" command. 2. Perhaps you want to add some content. You can add single files with "hugo new <SECTIONNAME>/<FILENAME>.<FORMAT>". 3. Start the built-in live server via "hugo server". Visit https://gohugo.io/ for quickstart guide and full documentation.

      Instead of installing an existing theme, you’ll add a small amount of HTML and CSS to your site to define how it looks. Existing themes can often require a lot of configuration, and that’s outside of the scope of this tutorial.

      Switch to the sharkopedia directory:

      Your Hugo site has the following structure:

      Output

      ├── archetypes ├── config.toml ├── content ├── data ├── layouts ├── resources ├── static └── themes
      • archetypes are your content templates. You can use the hugo command to create new Markdown pages, and it’ll use the files in the archetypes directory as the template for those pages.
      • config.toml is the configuration file for the site, where you specify the site’s domain, title, and the theme you want to use.
      • content is the directory that holds your site’s content.
      • data is where you can store JSON files you can use when generating your site.
      • layouts is where you place the HTML files that define your site’s look and feel, or override the templates from a theme.
      • resources is where Hugo places files it generates, like optimized images.
      • static holds static assets, like files, stylesheets, scripts, or other assets that you don’t need Hugo to manage for you.
      • themes contains themes you create or download.

      You won’t use a theme in this tutorial; you’ll define HTML files in the layouts directory to define the way your site looks.

      Before moving on, open the file config.toml in your editor. Change the baseURL field to an empty string, and modify the title so it says “Sharkopedia”:

      config.toml

      baseURL = ""
      languageCode = "en-us"
      title = "Sharkopedia"
      

      Save the file.

      Next, you’ll create the layout and content for the site. The site will have a home page and a section called “Sharks”. To display your content, Hugo needs three types of template files:

      • A template for the home page.
      • A template for a page of content, like a page about a single shark.
      • A template that shows a list of pages, such as a page that lists all the sharks, or all of the tags or categories on the site.

      Let’s start by creating the home page template. Create the file layouts/index.html and open it in your editor. Add the following code to the file to define the site:

      layouts/index.html

      <!DOCTYPE html>
      <html lang="en-US">
        <head>
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width, initial-scale=1">
          <title><^>{{ .Site.Title }}</title>
          <link rel="stylesheet" href="https://www.digitalocean.com/style.css">
        </head>
        <body>
      
          <header>
            <h1>{{ .Site.Title }}</h1>
          </header>
      
          <main>
            <h2>{{ .Title }}</h2>
            {{ .Content }}
          </main>
      
          <footer>
            <small>Made with love and Hugo</small>
          </footer>
        </body>
      </html>
      

      The {{ .Site.Title }} lines grab the title from the config.toml file. The {{ .Title }} line and {{ .Content }} line grab the title and content from the document associated with the home page, which you’ll create next.

      Save your file.

      By default, Hugo creates all new pages in draft mode. Open the file archetypes/default.md in your editor and modify it so that draft is false. This way all new pages you create won’t be in draft mode.

      archetypes/default.md

      ---
      title: "{{ replace .Name "-" " " | title }}"
      date: {{ .Date }}
      draft: false
      ---
      

      The replace line in the title field tells Hugo to generate the page’s title based on the filename.

      Save the file.

      Now use Hugo to generate a content file for your home page. From the terminal, in the directory of your project, type this command:

      This generates the file content/index.md:

      Output

      /Users/your_username/sharkopedia/content/_index.md created

      The underscore in the filename tells Hugo that this is the content page for either a listing page or the home page, as opposed to a regular piece of content.

      Open the content/_index.md file in your editor and add some text and change the title:

      content/_index.md

      ---
      title: "Welcome"
      date: 2020-10-07T14:07:35-05:00
      draft: false
      ---
      This is a site all about sharks! Select a shark from the list to learn more:
      

      The content in this file will be placed on the home page. Let’s test it out.

      From the terminal, launch Hugo’s development server with the following command:

      Visit http://localhost:1313 in your web browser and you’ll see your home page:

      The home page

      Once you’ve verified that the site is working, press CTRL+C to stop the server.

      Next you’ll need a template for single pieces of content, and for this project, you can duplicate the home page, although you’ll have to place it in a specific directory.

      Create the directory layouts/_default:

      Then create the file layouts/_default/single.html and copy the contents of your layouts/index.html file into the new file. You can do this from the command line with this command:

      • cp layouts/index.html layouts/_default/single.html

      Next, you’ll create a sharks content section of the site. To do so, you’ll use the hugo command to create new Markdown files in the content directory under a sharks subdirectory. Execute this command to create a content page for Hammerhead sharks:

      • hugo new sharks/hammerhead.md

      Note that you don’t specify the content directory when using the hugo new command.

      Now launch Hugo’s development server:

      Visit http://localhost:1313/sharks/hammerhead.md to see your page for Hammerhead sharks:

      Hammerhead page

      If you visit http://localhost:1313/sharks, you won’t see anything because you haven’t defined the final template you need: the template that Hugo uses to display lists of content. Let’s do that now.

      Stop the server by pressing CTRL+C.

      Create the file layouts/_default/list.html and open it in your editor. Inside the file, place the same content as your other templates:

      layouts/_default/list.html

      <!DOCTYPE html>
      <html lang="en-US">
        <head>
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width, initial-scale=1">
          <title><^>{{ .Site.Title }}</title>
          <link rel="stylesheet" href="https://www.digitalocean.com/style.css">
        </head>
        <body>
      
          <header>
            <h1>{{ .Site.Title }}</h1>
          </header>
      
          <main>
            <h2>{{ .Title }}</h2>
            {{ .Content }}
          </main>
      
          <footer>
            <small>Made with love and Hugo</small>
          </footer>
        </body>
      </html>
      

      Inside the <main> tag, after the title and content, place the following code which generates a bulleted list of pages to display:

          <main>
            <h2>{{ .Title }}</h2>
            {{ .Content }}
      
            <ul>
            {{ range .Pages }}
              <li><a href="https://www.digitalocean.com/community/tutorials/{{ .RelPermalink }}">{{ .Title }}</a></li>
            {{ end }}
            </ul>
          </main>
      
      

      The range function iterates over all of the pages for the section of the site. The actual value of .Pages is determined when Hugo generates your site. This list template you created will be used as the default template for any lists, including tag pages, category pages, and your “sharks” section. You can make more specific templates for your sections, but this gives you a default layout that works everywhere. Save the file.

      Finally, create pages for Mako sharks and whale sharks so there’s more content to display:

      • hugo new sharks/mako.md
      • hugo new sharks/whale.md

      Start the server again with hugo serve and visit http://localhost:1313/sharks and you’ll see the three Shark pages listed:

      The sharks page with all three pages listed

      Stop the server with CTRL+C.

      Your site is ready. Next you’ll push your code to GitHub so you can deploy it.

      Step 3 — Pushing the Site to GitHub

      DigitalOcean App Platform deploys your code from GitHub repositories, so the first thing you’ll need to do is get your site in a Git repository and push that repository to GitHub.

      First, initialize your Sharkopedia project as a Git repository:

      When you generate your site, Hugo will place files in a directory called public. Let’s exclude that directory by adding it to Git’s ignore list. Create a new file called .gitignore and add the following code to the file:

      .gitignore

      public
      

      Save the file.

      Now execute the following command to add files to your repository:

      • git add archetypes/ config.toml content/ .gitignore layouts/

      You’ll notice that the data, themes, resources, static, and themes aren’t included in this command; those directories are empty and Git only stores files, not directories. If you add your own data, themes, or static content later, you’ll add those directories later.

      Make your initial commit:

      • git commit -m "Initial version of the site"

      Your files will commit:

      Output

      [master (root-commit) b045f24] First version of the site 10 files changed, 114 insertions(+) create mode 100644 .gitignore create mode 100644 archetypes/default.md create mode 100644 config.toml create mode 100644 content/_index.md create mode 100644 content/sharks/hammerhead.md create mode 100644 content/sharks/mako.md create mode 100644 content/sharks/whale.md create mode 100644 layouts/_default/list.html create mode 100644 layouts/_default/single.html create mode 100644 layouts/index.html

      Open your browser and navigate to GitHub, log in with your profile, and create a new repository called sharkopedia. Create an empty repository without a README or license file.

      Once you’ve created the repository, return to the command line to push your local files to GitHub.

      First, add GitHub as a remote repository:

      • git remote add https://github.com/your_username/sharkopedia

      Next, rename the default branch main, to match what GitHub expects:

      Finally, push your main branch to GitHub’s main branch:

      Your files will transfer:

      Output

      Enumerating objects: 16, done. Counting objects: 100% (16/16), done. Delta compression using up to 6 threads Compressing objects: 100% (14/14), done. Writing objects: 100% (16/16), 1.58 KiB | 1.58 MiB/s, done. Total 16 (delta 1), reused 0 (delta 0), pack-reused 0 remote: Resolving deltas: 100% (1/1), done. To https://github.com/your_username/sharkopedia * [new branch] main -> main Branch 'main' set up to track remote branch 'main' from 'origin'.

      Enter your GitHub credentials when prompted to push your code.

      You’re ready to deploy your site to DigitalOcean’s App Platform.

      Step 4 — Deploying to DigitalOcean with App Platform

      Once the code is pushed, visit https://cloud.digitalocean.com/apps and click Launch Your App. You’ll be prompted to connect your GitHub account:

      Connect GitHub account

      Connect your account and allow DigitalOcean to access your repositories. You can choose to let DigitalOcean have access to all of your repositories, or just to the ones you wish to deploy.

      Allow repository access

      Press Install and Authorize. You’ll be returned to your DigitalOcean dashboard to continue creating your app.

      Once your GitHub account is connected, select the your_account/sharkopedia repository and click Next.

      Choose your repository

      Next, provide your app’s name, choose a region, and ensure the main branch is selected. Then ensure that Autodeploy code changes is checked. Press Next to continue.

      Choose name, region, and branch

      DigitalOcean will detect that your project is a Hugo site and will automatically populate the command to build your site.

      Hugo site detected and build command populated

      Press Next and you’ll be directed to the Finalize and Launch screen where you’ll choose your plan. Static sites are free, so choose Starter App and press Launch Starter App at the bottom. Your site will build:

      Site building and deploying

      Once the build process completes, the interface will show you a healthy site and provide a link for you to visit the site:

      [The deployed site in the dashboard](blob:https://imgur.com/874b4f40-5163-4ef3-82c3-4602a1ec0912)

      Now that your site is deployed, you can make changes by pushing your code to GitHub.

      Step 5 — Deploying Changes

      To ensure that changes get deployed, let’s add the list of sharks to the home page of the site. When you commit the changes to your repository and push them to GitHub, they’ll deploy automatically.

      Open the file layouts/index.html in your editor and add the following code to iterate over all the pages of your site that are sharks and display them:

      layouts/index.html

      ...
          <main>
            <h2>{{ .Title }}</h2>
            {{ .Content }}
      
            <ul>
            {{ range (where site.RegularPages "Type" "in" "sharks") }}
              <li><a href="https://www.digitalocean.com/community/tutorials/{{ .RelPermalink }}">{{ .Title }}</a></li>
            {{ end }}
            </ul>
          </main>
      

      This version uses (where site.RegularPages "Type" "in" "sharks") to find only the content pages for sharks. Unlike your default list template, your home page needs more direction about what kind of content to display.

      Save the file. Run the server with hugo serve and visit http://localhost:1313 to see your sharks listed:

      Sharks on the home page

      Press CTRL+C to stop the server.

      Now add the updated file to your repository:

      • git add layouts/index.html

      Make a commit:

      • git commit -m "Add sharks to home page"

      Finally, push your code to GitHub:

      Within a few moments, your changes will be deployed. If you switch back to your DigitalOcean App status page, you’ll see the progress bar deploying your app again:

      Redeploy progress

      Once it finishes, visit your site to see your changes live.

      Conclusion

      In this tutorial you built a basic Hugo website and deployed using DigitalOcean’s App Platform. Any changes you commit and push to your repository will be redeployed, so you can now expand your site. You can find the example code for this tutorial in the DigitalOcean Community Repository

      The example in this tutorial is a minimal Hugo site. Your own site may have more complex themes and features, but the deployment process will be the same.



      Source link