One place for hosting & domains

      WordPress

      How To Embed a React Application in WordPress on Ubuntu 18.04


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

      Introduction

      WordPress is a popular content management system that, according to W3Techs (Web Technology Surveys), powers over 33% of websites on the Internet. One reason it is so popular is that it is easy to set up with clear, straight-forward documentation. In addition, there are a great deal of community resources supporting WordPress developers. WordPress can solve many use-cases with an inexpensive or even free out-of-the-box solution. Finally, WordPress comes with a well-defined plugin system, which allows developers to write custom code to add their own functionality. This plugin system is well-documented, works well, and as you will see later in this tutorial, is easy to use.

      Developers who want to deliver the richest, most interactive experiences can use JavaScript, supported by frameworks such as React. React is a JavaScript library that is designed to make it easy for developers to create dynamic, interactive UIs that go above and beyond a typical static page or form. Created by Facebook, and thus well maintained for security, stability, and ease of use, React is popular because it is has good documentation and a well-established, community-driven ecosystem of documentation and plugins.

      This tutorial will walk you through best practices for embedding a React application in a WordPress site. For its example, it will use a common use case: creating a widget intended to be embedded on multiple pages and sometimes multiple times on a page. On the server side, it will be implemented as a WordPress shortcode. A shortcode is like an HTML tag, but it uses square brackets ([…]) instead of angle brackets (<…>). Instead of rendering an HTML element directly, it invokes a PHP function, which in turn renders HTML, interpolated with data from the database.

      By the end of this tutorial, you will have created your own shortcode, inserted it into a page in WP Admin, and published that page. On that page, you will be able to see your React widget displayed by the browser.

      Prerequisites

      In order to follow this tutorial, you must have:

      • An Ubuntu 18.04 server set up with the Initial Server Setup with Ubuntu 18.04 tutorial to configure a firewall for your server along with a new user who has root privileges.
      • A fully registered domain name. This tutorial will use your_domain as an example throughout. You can purchase a domain name on Namecheap, get one for free on Freenom, or use the domain registrar of your choice.
      • Both of the following DNS records set up for your server. You can follow this introduction to DigitalOcean DNS for details on how to add them.

        • An A record with your_domain pointing to your server’s public IP address.
        • An A record with www.your_domain pointing to your server’s public IP address.
      • Installations of Apache, MySQL, and PHP on your server. You can get this by following How To Install Linux, Apache, MySQL, PHP (LAMP) stack on Ubuntu 18.04.

      • Secured Apache with Let’s Encrypt by following How To Secure Apache with Let’s Encrypt on Ubuntu 18.04 to generate a free SSL certificate.

      • A WordPress installation, which you can get by following How To Install WordPress with LAMP on Ubuntu 18.04 and its prerequisites.

      • Installation of Node.js by following the “Installing Using a PPA” option in How To Install Node.js on Ubuntu 18.04. This tutorial will be using version 11.15.0, so when using curl to download the installation script, replace 10.x with 11.x to follow along with the procedure in this tutorial.

      Step 1 — Updating and Configuring Filesystem Permissions

      When logged in as the non-root user created in the Initial Server Setup with Ubuntu 18.04 prerequisite, you will not have access to view or edit any files in the WordPress directory. This is a problem, as you will be adding and modifying files later to create your WordPress plugin and your React application. To fix this problem, in this step you will update your WordPress configuration so that you have access to edit your WordPress files.

      Run the following command, substituting sammy for the name of your non-root user and /var/www/wordpress for the path to your WordPress directory (which is the Apache document root folder you created in the prerequisite):

      • sudo chown -R sammy:www-data /var/www/wordpress

      Let’s break down this command:

      • sudo — This allows you to execute this command as root, since you are modifying files sammy does not have access to.
      • chown — This command changes file ownership.
      • -R — This flag changes the ownership recursively, including all subfolders and files.
      • sammy:www-data — This sets the owner as your non-root user (sammy) and keeps the group as www-data so that Apache can still access the files in order to serve them.
      • /var/www/wordpress — This specifies the path to your WordPress directory. This is the directory on which the ownership will change.

      To verify that this command was successful, list out the contents of the WordPress directory:

      • ls -la /var/www/wordpress

      You will see a listing of the contents of the directory:

      Output

      total 216 drwxr-x--- 5 sammy www-data 4096 Apr 13 15:42 . drwxr-xr-x 4 root root 4096 Apr 13 15:39 .. -rw-r----- 1 sammy www-data 235 Apr 13 15:54 .htaccess -rw-r----- 1 sammy www-data 420 Nov 30 2017 index.php -rw-r----- 1 sammy www-data 19935 Jan 1 20:37 license.txt -rw-r----- 1 sammy www-data 7425 Jan 9 02:56 readme.html -rw-r----- 1 sammy www-data 6919 Jan 12 06:41 wp-activate.php drwxr-x--- 9 sammy www-data 4096 Mar 13 00:18 wp-admin -rw-r----- 1 sammy www-data 369 Nov 30 2017 wp-blog-header.php -rw-r----- 1 sammy www-data 2283 Jan 21 01:34 wp-comments-post.php -rw-r----- 1 sammy www-data 2898 Jan 8 04:30 wp-config-sample.php -rw-r----- 1 sammy www-data 3214 Apr 13 15:42 wp-config.php drwxr-x--- 6 sammy www-data 4096 Apr 13 15:54 wp-content -rw-r----- 1 sammy www-data 3847 Jan 9 08:37 wp-cron.php drwxr-x--- 19 sammy www-data 12288 Mar 13 00:18 wp-includes -rw-r----- 1 sammy www-data 2502 Jan 16 05:29 wp-links-opml.php -rw-r----- 1 sammy www-data 3306 Nov 30 2017 wp-load.php -rw-r----- 1 sammy www-data 38883 Jan 12 06:41 wp-login.php -rw-r----- 1 sammy www-data 8403 Nov 30 2017 wp-mail.php -rw-r----- 1 sammy www-data 17947 Jan 30 11:01 wp-settings.php -rw-r----- 1 sammy www-data 31085 Jan 16 16:51 wp-signup.php -rw-r----- 1 sammy www-data 4764 Nov 30 2017 wp-trackback.php -rw-r----- 1 sammy www-data 3068 Aug 17 2018 xmlrpc.php

      These files are the ones included in the WordPress core in the file named latest.tar.gz that you downloaded from wordpress.org in the prerequisite How To Install WordPress with LAMP on Ubuntu 18.04. If the permissions appear as they do in the preceding output, this means that your files and directories have been updated correctly.

      In this step, you updated your WordPress installation to give yourself access to edit its files. In the next step, you will use that access to create files that will compose a WordPress plugin.

      Step 2 — Creating a Basic WordPress Plugin

      Now that you have access to modify files in the WordPress directory, you will create a basic WordPress plugin and add it to the installation. This will allow React to interact with WordPress later in the tutorial.

      A WordPress plugin can be as simple as:

      1. A directory inside wp-content/plugins.
      2. A file inside that directory with the same name and a .php file extension.
      3. A special comment at the top of that file that provides WordPress with important plugin metadata.

      To make a plugin for the React code you will write later, start by creating a directory for the WordPress plugin. For simplicity, this tutorial will name the plugin react-wordpress. Run the following command, replacing wordpress with your Apache document root:

      • mkdir /var/www/wordpress/wp-content/plugins/react-wordpress

      Then, navigate to the newly-created directory. Subsequent commands will be executed from here.

      • cd /var/www/wordpress/wp-content/plugins/react-wordpress

      Let’s create the plugin file now. This tutorial will use nano, invoked with the command nano, as the command line text editor for all files. You are also free to use any other text editor of your choice, such as Pico, Vim, or Emacs.

      Open up react-wordpress.php for editing:

      Add the following lines to your file to create the start of the plugin:

      /var/www/wordpress/wp-content/plugins/react-wordpress/react-wordpress.php

      <?php
      /**
       * @wordpress-plugin
       * Plugin Name:       Embedding React In WordPress
       */
      
      defined( 'ABSPATH' ) or die( 'Direct script access disallowed.' );
      

      The commented section at the top provides metadata for the plugin, and the line that checks for the ABSPATH constant prevents a bad actor from accessing this script directly by its URL. ABSPATH is the absolute path to your WordPress root directory, so if ABSPATH is defined, you can be sure the file was loaded through the WordPress environment.

      Note: Many fields are available for a plugin metadata comment, but only Plugin Name is required. See the Header Requirements page in the WordPress documentation for more details.

      Next, open up a web browser and navigate to the Plugins page of your domain (https://your_domain/wp-admin/plugins.php). You will see your plugin listed along with WordPress’s default plugins:

      WP Admin Plugins Page

      Click Activate to enable your plugin.

      Once you have activated your plugin, the row containing your plugin will be highlighted in blue, with a blue border on the left, and instead of a link below it that says Activate, there will be one that says Deactivate:

      WP Admin Plugins Page After Plugin Activation

      Next, you will establish the structure of your plugin.

      Go back to your terminal to open react-wordpress.php:

      Then update it to add the following highlighted lines, which define useful constants:

      /var/www/wordpress/wp-content/plugins/react-wordpress/react-wordpress.php

      <?php
      /**
       * @wordpress-plugin
       * Plugin Name:       Embedding React In WordPress
       */
      
      defined( 'ABSPATH' ) or die( 'Direct script access diallowed.' );
      
      define( 'ERW_WIDGET_PATH', plugin_dir_path( __FILE__ ) . '/widget' );
      define( 'ERW_ASSET_MANIFEST', ERW_WIDGET_PATH . '/build/asset-manifest.json' );
      define( 'ERW_INCLUDES', plugin_dir_path( __FILE__ ) . '/includes' );
      

      In the newly added lines, you defined three constants:

      1. ERW_WIDGET_PATH — This will be the path to the React application.
      2. ERW_ASSET_MANIFEST — This is the path to the React asset manifest, a file that contains the list of JavaScript and CSS files that need to be included on the page for your application to work.
      3. ERW_INCLUDES — This subdirectory will contain all of the PHP files.

      Note that each define() refers to plugin_dir_path( __FILE__ ). That stands for the directory path to that file.

      After adding the constant definitions, save the file and exit the editor.

      Note: It is important to namespace your constants. In this case we are using the namespace ERW_, which stands for Embedding React in WordPress. Prefixing variables with this namespace ensures they are unique so that they don’t conflict with constants defined in other plugins.

      To create the includes/ folder, which will contain the other PHP files, start at the top level of the plugin directory, /var/www/your_domain/wp-content/plugins/react-wordpress. Then, create the folder:

      Now that you’ve scaffolded the PHP-related files and folders needed to make a WordPress plugin, you will create the initial files and folders for React.

      Step 3 — Initializing the React Application

      In this step, you will use Create React App to initialize your React application.

      This tutorial was tested using Create React App version 3.0.1. Version 3.0.0 made breaking changes to the structure of asset-manifest.json, so this earlier version is not compatible with this tutorial without modifications. To ensure you are using the version expected here, run this command to install Create React App:

      • sudo npm install --global create-react-app@3.0.1

      This command will install version 3.0.1 of Create React App. The --global flag will install it system-wide. Installing system-wide ensures that when you run create-react-app (or npx create-react-app) without any path specified, you will use the version that you just installed.

      After installing Create React App, use it to create the React application. This tutorial will name the app widget:

      • sudo create-react-app widget

      This command uses npx, which is a binary that ships with NPM. It is designed to make it easy to use CLI tools and other executables that are hosted on NPM. It will install those tools if they are not found locally.

      The create-react-app command will generate a project folder and all of the necessary files for a basic React app. This includes an index.html file, starting JavaScript, CSS, and test files, and a package.json for defining your project and dependencies. It pre-includes dependencies and scripts that let you build your application for production without needing to install and configure any additional build tools.

      Once you have set up the widget app, the output in the terminal will look something like this:

      Output

      … Success! Created widget at /var/www/wordpress/wp-content/plugins/react-wordpress/widget Inside that directory, you can run several commands: npm start Starts the development server. npm run build Bundles the app into static files for production. npm test Starts the test runner. npm run eject Removes this tool and copies build dependencies, configuration files and scripts into the app directory. If you do this, you can’t go back! We suggest that you begin by typing: cd widget npm start Happy hacking!

      Next, navigate to the newly created directory:

      You will now be able to build your application using the default build command, npm run build. This build command looks at the file package.json under the key scripts for a script named build:

      /var/www/wordpress/wp-content/plugins/react-wordpress/widget/package.json

      {
        "name": "widget",
        "version": "0.1.0",
        "private": true,
        "dependencies": {
          "react": "^16.9.0",
          "react-dom": "^16.9.0",
          "react-scripts": "3.1.1"
        },
        "scripts": {
          "start": "react-scripts start",
          "build": "react-scripts build",
          "test": "react-scripts test",
          "eject": "react-scripts eject"
        },
        "eslintConfig": {
          "extends": "react-app"
        },
        "browserslist": {
          "production": [
            ">0.2%",
            "not dead",
            "not op_mini all"
          ],
          "development": [
            "last 1 chrome version",
            "last 1 firefox version",
            "last 1 safari version"
          ]
        }
      }
      

      This calls the react-scripts.js executable provided by the react-scripts node module, which is one of the core components provided by create-react-app. This in turn calls the build script, which uses webpack to compile your project files into static asset files your browser understands. It does this by:

      • Resolving dependencies.
      • Compiling SASS files into CSS and JSX or TypeScript into JavaScript.
      • Transforming ES6 syntax into ES5 syntax with better cross-browser compatibility.

      Now that you know a bit about build, run the command in your terminal:

      Once the command completes, you will receive output similar to the following:

      Output

      > widget@0.1.0 build /var/www/wordpress/wp-content/plugins/react-wordpress/widget > react-scripts build Creating an optimized production build… Compiled successfully. File sizes after gzip: 36.83 KB (+43 B) build/static/js/2.6efc73d3.chunk.js 762 B (+44 B) build/static/js/runtime~main.a8a9905a.js 710 B (+38 B) build/static/js/main.2d1d08c1.chunk.js 539 B (+44 B) build/static/css/main.30ddb8d4.chunk.css The project was built assuming it is hosted at the server root. You can control this with the homepage field in your package.json. For example, add this to build it for GitHub Pages: "homepage" : "http://myname.github.io/myapp", The build folder is ready to be deployed. You may serve it with a static server: npm install -g serve serve -s build Find out more about deployment here: https://bit.ly/CRA-deploy

      Your project is now built, but before moving to the next step, it is a best practice to ensure that your application only loads if it is present.

      React uses an HTML element in the DOM inside of which it renders the application. This is called the target element. By default, this element has the ID root. To ensure that this root node is the app you are creating, alter src/index.js to check the ID of the target for the namespaced erw-root. To do this, first open src/index.js:

      Modify and add the highlighted lines:

      /var/www/wordpress/wp-content/plugins/react-wordpress/widget/src/index.js

      import React from 'react';
      import ReactDOM from 'react-dom';
      import './index.css';
      import App from './App';
      import * as serviceWorker from './serviceWorker';
      
      const target = document.getElementById('erw-root');
      if (target) { ReactDOM.render(<App />, target); }
      
      serviceWorker.unregister();
      

      Finally, save and quit the file when you are done editing.

      In this file, you made two important changes to the default index.js file:

      1. You changed the target element from <div id="root"></div> to <div id="erw-root"></div> so it is namespaced for your application.
      2. You enclosed the call to ReactDOM.render() in an if (…) statement so that the app is only loaded if it is present.

      Note: If you expect the widget to be present on every page, you may also wish to add a line of error handling, which prints a message to the console if an element with ID erw-root is not found. However, this tutorial will omit this step. A line like this would produce a console error on every page that does not have the element, including ones in which you are not planning to include the element. These multiple JavaScript console errors can risk lowering the search engine rankings for your site.

      After changing any JavaScript or CSS file in your src/ directory, it is important to recompile your app so that your changes are incorporated. To rebuild your app, run:

      Now your build/ directory contains a working React application in the form of JavaScript and CSS files. The next step involves setting up some PHP files that will enqueue your JavaScript and CSS in the page.

      Step 4 — Enqueueing the JavaScript and CSS Files

      In this step, you will use WordPress actions and filters to:

      1. Output the script-enqueueing code at the appropriate time in the WordPress page load cycle.
      2. Enqueue your JavaScript and CSS files in a way that least impacts page load speed.

      WordPress uses actions and filters as its primary hooks. Actions make it possible to execute code at a specified time in the page load cycle, and filters modify specific behavior by changing the return value of functions you do not otherwise own.

      To use these hooks, you will create a PHP file that will contain the code that parses the asset manifest. This is the same file you will use later to enqueue all of the assets so the scripts are written into the <head> tag.

      Before creating the file, use the following command to navigate out of the directory containing your React app and into the top-level react-wordpress plugin directory:

      • cd /var/www/wordpress/wp-content/plugins/react-wordpress

      Create the enqueue.php file inside the includes/ folder:

      • nano includes/enqueue.php

      Start by placing the opening <?php tag at the top of the file. Also add the line that checks for ABSPATH, which as discussed before is a best practice in every PHP file:

      /var/www/wordpress/wp-content/plugins/react-wordpress/includes/enqueue.php

      <?php
      // This file enqueues scripts and styles
      
      defined( 'ABSPATH' ) or die( 'Direct script access disallowed.' );
      

      Save and quit this file.

      Then, update react-wordpress.php to require enqueue.php from the project. First, open up the file for editing:

      Add the following highlighted line:

      /var/www/wordpress/wp-content/plugins/react-wordpress/react-wordpress.php

      <?php
      /**
       * @wordpress-plugin
       * Plugin Name:       Embedding React In WordPress
       */
      
      defined( 'ABSPATH' ) or die( 'Direct script access diallowed.' );
      
      define( 'ERW_WIDGET_PATH', plugin_dir_path( __FILE__ ) . '/widget' );
      define( 'ERW_ASSET_MANIFEST', ERW_WIDGET_PATH . '/build/asset-manifest.json' );
      define( 'ERW_INCLUDES', plugin_dir_path( __FILE__ ) . '/includes' );
      
      require_once( ERW_INCLUDES . '/enqueue.php' );
      

      It is a common pattern in WordPress plugins to require other PHP files from the includes/ directory in order to split important tasks into chunks. The require_once() function parses the contents of the file passed as an argument as though that file’s PHP code were written right there inline. Unlike the similar command include, require will raise an exception if the file you are trying to require cannot be found. Using require_once() (as opposed to just require()) ensures that enqueue.php will not be parsed multiple times if the directive require_once( ERW_INCLUDES . '/enqueue.php' ); is given multiple times.

      Save and exit the file.

      Now reopen includes/enqueue.php:

      • nano includes/enqueue.php

      Then, add the following highlighted code:

      /var/www/wordpress/wp-content/plugins/react-wordpress/includes/enqueue.php

      <?php
      // This file enqueues scripts and styles
      
      defined( 'ABSPATH' ) or die( 'Direct script access diallowed.' );
      
      add_action( 'init', function() {
      
        add_filter( 'script_loader_tag', function( $tag, $handle ) {
          if ( ! preg_match( '/^erw-/', $handle ) ) { return $tag; }
          return str_replace( ' src', ' async defer src', $tag );
        }, 10, 2 );
      
        add_action( 'wp_enqueue_scripts', function() {
      
        });
      });
      

      Adding a function to the init action means that this code will be run during the init phase of the load process, which is after your theme and other plugins have loaded.

      Setting the async and defer attributes on the <script> tags using the script_loader_tag filter tells the browser to load the scripts asynchronously instead of blocking DOM construction and page rendering.

      The wp_enqueue_scripts action then enqueues front-end items. See this page for more details.

      Be sure to write the file and exit.

      You have now told WordPress to write script and stylesheet tags to the page. In this next step, you will parse a file called the asset manifest. This will give you the paths to all of the files that you’ll need to enqueue.

      Step 5 — Parsing the Asset Manifest

      In this step, you will parse the asset manifest generated by the React build into a list of JavaScript and CSS files.

      When you build the application, the React build script will build your project into multiple JavaScript and CSS files. The files quantity and names will vary from one build to the next, as each one includes a hash of the file’s contents. The asset manifest provides the name of each file generated in the last build along with the path to that file. By parsing it programatically, you are guaranteed that script and stylesheet tags you write to the page will always point to the right files, even when the names change.

      First, examine the asset-manifest.json with the cat command:

      • cat widget/build/asset-manifest.json

      It will look something like this:

      Output

      { "files": { "main.css": "/static/css/main.2cce8147.chunk.css", "main.js": "/static/js/main.a284ff71.chunk.js", "main.js.map": "/static/js/main.a284ff71.chunk.js.map", "runtime~main.js": "/static/js/runtime~main.fa565546.js", "runtime~main.js.map": "/static/js/runtime~main.fa565546.js.map", "static/js/2.9ca06fd6.chunk.js": "/static/js/2.9ca06fd6.chunk.js", "static/js/2.9ca06fd6.chunk.js.map": "/static/js/2.9ca06fd6.chunk.js.map", "index.html": "/index.html", "precache-manifest.e40c3c7a647ca45e36eb20f8e1a654ee.js": "/precache-manifest.e40c3c7a647ca45e36eb20f8e1a654ee.js", "service-worker.js": "/service-worker.js", "static/css/main.2cce8147.chunk.css.map": "/static/css/main.2cce8147.chunk.css.map", "static/media/logo.svg": "/static/media/logo.5d5d9eef.svg" } }

      To parse it, your code will look for object keys that end with .js and .css.

      Open up your enqueue.php file:

      • nano includes/enqueue.php

      Add the highlighted snippet:

      /var/www/wordpress/wp-content/plugins/react-wordpress/includes/enqueue.php

      <?php
      // This file enqueues scripts and styles
      
      defined( 'ABSPATH' ) or die( 'Direct script access disallowed.' );
      
      add_action( 'init', function() {
      
        add_filter( 'script_loader_tag', function( $tag, $handle ) {
          if ( ! preg_match( '/^erw-/', $handle ) ) { return $tag; }
          return str_replace( ' src', ' async defer src', $tag );
        }, 10, 2 );
      
        add_action( 'wp_enqueue_scripts', function() {
      
          $asset_manifest = json_decode( file_get_contents( ERW_ASSET_MANIFEST ), true )['files'];
      
          if ( isset( $asset_manifest[ 'main.css' ] ) ) {
            wp_enqueue_style( 'erw', get_site_url() . $asset_manifest[ 'main.css' ] );
          }
      
          wp_enqueue_script( 'erw-runtime', get_site_url() . $asset_manifest[ 'runtime~main.js' ], array(), null, true );
      
          wp_enqueue_script( 'erw-main', get_site_url() . $asset_manifest[ 'main.js' ], array('erw-runtime'), null, true );
      
          foreach ( $asset_manifest as $key => $value ) {
            if ( preg_match( '@static/js/(.*).chunk.js@', $key, $matches ) ) {
              if ( $matches && is_array( $matches ) && count( $matches ) === 2 ) {
                $name = "erw-" . preg_replace( '/[^A-Za-z0-9_]/', '-', $matches[1] );
                wp_enqueue_script( $name, get_site_url() . $value, array( 'erw-main' ), null, true );
              }
            }
      
            if ( preg_match( '@static/css/(.*).chunk.css@', $key, $matches ) ) {
              if ( $matches && is_array( $matches ) && count( $matches ) == 2 ) {
                $name = "erw-" . preg_replace( '/[^A-Za-z0-9_]/', '-', $matches[1] );
                wp_enqueue_style( $name, get_site_url() . $value, array( 'erw' ), null );
              }
            }
          }
      
        });
      });
      

      When you are done, write and quit the file.

      The highlighted code does the following:

      1. Reads the asset manifest file and parses it as a JSON file. It accesses the content stored at the key 'files' and stores it to the $asset_manifest variable.
      2. Enqueues the main CSS file if it exists.
      3. Enqueues the React runtime first, then the main JavaScript file, setting the runtime as a dependency to ensure it is loaded in the page first.
      4. Parses the asset manifest file list for any JavaScript files named static/js/<hash>.chunk.js and enqueues them in the page after the main file.
      5. Parses the asset manifest file list for any CSS files named static/css/<hash>.chunk.css and enqueues them in the page after the main CSS file.

      Note: Using wp_enqueue_script() and wp_enqueue_style will cause <script> and <link> tags for the enqueued files to appear in every page. The last argument true tells WordPress to place the file below the page content footer instead of at the bottom of the <head> element. This is important so that loading the JavaScript files doesn’t slow down the rest of the page.

      In this step, you isolated the filepaths of the scripts and styles used by your app. In the next step, you will ensure that those filepaths point to your React app’s build directory and that none of your source files are accessible from the browser.

      Step 6 — Serving and Securing Static Files

      At this point, you have told WordPress which JavaScript and CSS files to load and where to find them. However, if you visit https://your_domain in the browser and look at the JavaScript console, you will see HTTP 404 errors. (Check out this article for more info on how to use the JavaScript console.)

      404 Errors in the JavaScript Console

      This is because the URL route to the file (e.g., /static/js/main.2d1d08c1.chunk.js) does not match the actual path to the file (e.g., /wp-content/plugins/react-wordpress/widget/build/static/js/main.2d1d08c1.chunk.js).

      In this step, you will correct this issue by telling React where the build directory is located. You will also add an Apache rewrite rule to the .htaccess file to protect your source files from being viewed in the browser.

      To give React the correct path to your app, open package.json inside of your React application’s directory:

      • sudo nano widget/package.json

      Then, add the highlighted homepage line:

      /var/www/wordpress/wp-content/plugins/react-wordpress/widget/package.json

      {
        "name": "widget",
        "version": "0.1.0",
        "private": true,
        "homepage": "/wp-content/plugins/react-wordpress/widget/build",
        "dependencies": {
          "react": "^16.9.0",
          "react-dom": "^16.9.0",
          "react-scripts": "3.1.1"
        },
        "scripts": {
          "start": "react-scripts start",
          "build": "react-scripts build",
          "test": "react-scripts test",
          "eject": "react-scripts eject"
        },
        "eslintConfig": {
          "extends": "react-app"
        },
        "browserslist": {
          "production": [
            ">0.2%",
            "not dead",
            "not op_mini all"
          ],
          "development": [
            "last 1 chrome version",
            "last 1 firefox version",
            "last 1 safari version"
          ]
        }
      }
      

      Write and quit the file. Then, rebuild your React application. Move to the top level of widget/:

      Then run the build command:

      After the build command completes, inspect the asset manifest by outputting its contents to the terminal:

      • cat build/asset-manifest.json

      You will see that the file paths have all changed:

      /var/www/wordpress/wp-content/plugins/react-wordpress/widget/build/asset-manifest.json

      {
        "files": {
          "main.css": "/wp-content/plugins/react-wordpress/widget/build/static/css/main.2cce8147.chunk.css",
          "main.js": "/wp-content/plugins/react-wordpress/widget/build/static/js/main.a28d856a.chunk.js",
          "main.js.map": "/wp-content/plugins/react-wordpress/widget/build/static/js/main.a28d856a.chunk.js.map",
          "runtime~main.js": "/wp-content/plugins/react-wordpress/widget/build/static/js/runtime~main.2df87c4b.js",
          "runtime~main.js.map": "/wp-content/plugins/react-wordpress/widget/build/static/js/runtime~main.2df87c4b.js.map",
          "static/js/2.9ca06fd6.chunk.js": "/wp-content/plugins/react-wordpress/widget/build/static/js/2.9ca06fd6.chunk.js",
          "static/js/2.9ca06fd6.chunk.js.map": "/wp-content/plugins/react-wordpress/widget/build/static/js/2.9ca06fd6.chunk.js.map",
          "index.html": "/wp-content/plugins/react-wordpress/widget/build/index.html",
          "precache-manifest.233e0a9875cf4d2df27d6280d12b780d.js": "/wp-content/plugins/react-wordpress/widget/build/precache-manifest.233e0a9875cf4d2df27d6280d12b780d.js",
          "service-worker.js": "/wp-content/plugins/react-wordpress/widget/build/service-worker.js",
          "static/css/main.2cce8147.chunk.css.map": "/wp-content/plugins/react-wordpress/widget/build/static/css/main.2cce8147.chunk.css.map",
          "static/media/logo.svg": "/wp-content/plugins/react-wordpress/widget/build/static/media/logo.5d5d9eef.svg"
        }
      }
      

      This tells your app where to find the correct files, but also presents a problem: It exposes the path to your app’s src directory, and somebody who is familiar with create-react-app could visit https://your_domain/wp-content/plugins/react-wordpress/widget/src/index.js and start exploring the source files for your app. Try it yourself!

      To protect the paths you do not want users to access, add an Apache rewrite rule to your WordPress’s .htaccess file.

      • nano /var/www/wordpress/.htaccess

      Add the four highlighted lines:

      /var/www/wordpress/.htaccess

      <IfModule mod_rewrite.c>
      RewriteRule ^wp-content/plugins/react-wordpress/widget/(build|public)/(.*) - [L]
      RewriteRule ^wp-content/plugins/react-wordpress/widget/* totally-bogus-erw.php [L]
      </IfModule>
      
      # BEGIN WordPress
      <IfModule mod_rewrite.c>
      RewriteEngine On
      RewriteBase /
      RewriteRule ^index.php$ - [L]
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteRule . /index.php [L]
      </IfModule>
      
      # END WordPress
      

      This tells Apache to allow browser requests to anything at wp-content/plugins/react-wordpress/widget/build/ or wp-content/react-wordpress/widget/public/. Anything else will redirect to totally-bogus-erw.php. Unless you have a file named totally-bogus-erw.php at your top level, this request will be handled by WordPress, which will render a 404 error.

      There are WordPress plugins, such as Stream, that will monitor request activity and log 404s. In the logs, the request will show the IP address and the page requested when the user received the 404. Watching for totally-bogus-erw.php will tell you if a specific IP address is trying to crawl your React app’s src directory.

      Be sure to write and quit the file.

      Now that you have established the routing necessary to load your JavaScript and CSS files onto the page, it is time to use a shortcode to add HTML elements to the page that the JavaScript will interact with to render your app.

      Step 7 — Creating a Shortcode

      Shortcodes make it possible to insert complex HTML blocks interpolated with server-side data, with very simple in-page syntax. In this step, you will create and register a WordPress shortcode and use that to embed your application in the page.

      Navigate to the top level of your plugin:

      • cd /var/www/wordpress/wp-content/plugins/react-wordpress/

      Create a new PHP file that will contain the shortcode:

      • touch includes/shortcode.php

      Then, edit your main PHP file so that includes/shortcode.php is required when your plugin loads. First open react-wordpress.php:

      Then add the following highlighted line:

      /var/www/wordpress/wp-content/plugins/react-wordpress/react-wordpress.php

      <?php
      /**
       * @wordpress-plugin
       * Plugin Name:       Embedding React In WordPress
       */
      
      defined( 'ABSPATH' ) or die( 'Direct script access diallowed.' );
      
      define( 'ERW_WIDGET_PATH', plugin_dir_path( __FILE__ ) . '/widget' );
      define( 'ERW_ASSET_MANIFEST', ERW_WIDGET_PATH . '/build/asset-manifest.json' );
      define( 'ERW_INCLUDES', plugin_dir_path( __FILE__ ) . '/includes' );
      
      require_once( ERW_INCLUDES . '/enqueue.php' );
      require_once( ERW_INCLUDES . '/shortcode.php' );
      

      Write and quit the file.

      Now, open the newly created shortcode file:

      • nano includes/shortcode.php

      Add the following code:

      /var/www/wordpress/wp-content/plugins/react-wordpress/includes/shortcode.php

      <?php
      // This file enqueues a shortcode.
      
      defined( 'ABSPATH' ) or die( 'Direct script access disallowed.' );
      
      add_shortcode( 'erw_widget', function( $atts ) {
        $default_atts = array();
        $args = shortcode_atts( $default_atts, $atts );
      
        return "<div id='erw-root'></div>";
      });
      

      This code contains mostly boilerplate. It registers a shortcode named erw_widget that, when invoked, prints <div id="erw-root"></div>, the React app’s root element, to the page.

      Save and quit shortcode.php.

      To see the React app in action, you will need to create a new WordPress page and add the shortcode to it.

      Navigate to https://your_domain/wp-admin in a web browser. At the very top of the page, you’ll see a black bar that has the WordPress logo on the left, followed by a house icon, the name of your site, a comment bubble icon and number, and another link that says + New. Hover over the + New button and a menu will drop down. Click the menu item that says Page.

      Create a Page

      When the screen loads, your cursor will be focused in the text box that says Add title. Click there and start typing to give the new page a relevant title. This tutorial will use My React App:

      Giving the Page a Title

      Assuming you are using the WordPress Gutenberg editor, you will see a line of text near the top of the page, below the title, that reads Start writing or type / to choose a block. When you hover over that text, three symbols will appear on the right. Choose the nearest one that resembles [/] to add a shortcode block:

      Adding a Shortcode Block

      Type the shortcode [erw_widget] into the newly-added text area. Then, click the blue Publish… button in the upper right corner of the window, then press Publish to confirm.

      Type in Your Shortcode and Publish

      You will see a green bar confirming that the page has been published. Click the View Page link:

      Click Link to View Page

      On the screen, you will see your app:

      Working React App

      Now that you have a basic React app rendering in the page, you can customize that app with options provided server-side by an admin.

      Step 8 — Injecting Server-Generated Settings

      In this step, you will inject settings into the application using both server-generated data and user-provided data. This will enable you to display dynamic data in your application and to use the widget multiple times in a page.

      First, open the index.js file:

      • sudo nano widget/src/index.js

      Then, delete the import App from './App'; line and update the contents of index.js with the following highlighted lines:

      /var/www/wordpress/wp-content/plugins/react-wordpress/widget/src/index.js

      import React from 'react';
      import ReactDOM from 'react-dom';
      import './index.css';
      import * as serviceWorker from './serviceWorker';
      
      const App = () => (
        <div className="App">
          <span className="App__Message">Hello,<br />World!</span>
        </div>
      );
      
      const target = document.getElementById('erw-root');
      if (target) { ReactDOM.render(<App />, target); }
      
      serviceWorker.unregister();
      

      This modifies your React application so that instead of returning the default Create React App screen, it returns an element that reads Hello, World!.

      Save and quit the file. Then open index.css for editing:

      • nano widget/src/index.css

      Replace the contents of index.css with the following code:

      /var/www/wordpress/wp-content/plugins/react-wordpress/widget/src/index.css

      .App {
        width: 100px;
        height: 100px;
        border: 1px solid;
        display: inline-block;
        margin-right: 20px;
        position: relative;
      }
      
      .App .App__Message {
        font-size: 15px;
        line-height: 15px;
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
        text-align: center;
        width: 100%;
      }
      

      The styles for .App will render a 100-pixel square, with a solid border, and the styles for .App__Message will render text that is centered inside the square, both vertically and horizontally.

      Write and quit the file, then rebuild the application:

      • cd widget
      • sudo npm run build

      Once the build is successful, refresh https://your_domain/index.php/my-react-app/ in your browser. You will now see the box that you styled with CSS, along with the text Hello, World!:

      Simplified React Application

      Next, you will add custom settings, consisting of a user-provided border color and size. You will also pass the display name of the current user from the server.

      Updating the Shortcode to Accept Arguments

      To pass a user-provided argument, you must first give the user a way to pass an argument. Back in the terminal, navigate back to the top level of your plugin:

      Next, open your shortcode.php file for editing:

      • nano includes/shortcode.php

      Update your shortcode file to contain the following highlighted lines:

      /var/www/wordpress/wp-content/plugins/react-wordpress/includes/shortcode.php

      <?php
      // This file enqueues your shortcode.
      
      defined( 'ABSPATH' ) or die( 'Direct script access disallowed.' );
      
      add_shortcode( 'erw_widget', function( $atts ) {
        $default_atts = array( 'color' => 'black' );
        $args = shortcode_atts( $default_atts, $atts );
      
        return "<div class='erw-root'></div>";
      });
      

      Write and quit the file. Notice how the code adds 'color' => 'black' to the $default_atts array. The array key color instructs WordPress to expect that the color attribute might be passed to the [erw_widget] shortcode. The array value, black, sets the default value. All shortcode attributes are passed to the shortcode function as strings, so if you do not want to set a default value, you could use the empty string ('') instead. The last line changes to use a class instead of an ID because it is expected that there will be more than one of the element in the page.

      Now, go back to your browser and click the Edit button beneath your Hello, World! box. Update the WordPress page in your browser to add a second instance of the shortcode, and add a color attribute to both instances. This tutorial will use [erw_widget color="#cf6f1a"] and [erw_widget color="#11757e"]:

      Add a Second Widget

      Click the blue Update button to save.

      Note: The second widget will not display yet. You need to update the React app to expect multiple instances identified by a class instead of a single instance identified by an ID.

      Next, open index.js for editing:

      • sudo nano widget/src/index.js

      Update it with the following:

      /var/www/wordpress/wp-content/plugins/react-wordpress/widget/src/index.js

      import React from 'react';
      import ReactDOM from 'react-dom';
      import './index.css';
      import * as serviceWorker from './serviceWorker';
      
      const App = () => (
        <div className="App">
          <span className="App__Message">Hello,<br />World!</span>
        </div>
      );
      
      const targets = document.querySelectorAll('.erw-root');
      Array.prototype.forEach.call(targets, target => ReactDOM.render(<App />, target));
      
      serviceWorker.unregister();
      

      Write and quit the file. The updated lines will invoke the React app on each instance with the class erw-root. So if the shortcode is used twice, two squares will appear in the page.

      Finally, open index.css for editing:

      • sudo nano widget/src/index.css

      Update the file to contain the following highlighted line:

      /var/www/wordpress/wp-content/plugins/react-wordpress/widget/src/index.css

      .erw-root { display: inline-block; }
      
      .App {
        width: 100px;
        height: 100px;
        border: 1px solid;
        display: inline-block;
        margin-right: 20px;
        position: relative;
      }
      
      .App .App__Message {
        font-size: 15px;
        line-height: 15px;
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
        text-align: center;
        width: 100%;
      }
      

      With this added line, multiple adjacent widgets will appear side-by-side instead of one above the other.

      Save and quit the file.

      Now, re-compile your React app:

      • cd widget
      • sudo npm run build

      Now, if you refresh the page in your browser, you will see both widgets:

      Two Widgets

      Notice that the widgets still do not display the border color. This will be addressed in a future section.

      Uniquely Identifying Each Widget Instance

      In order to uniquely identify each widget, it is necessary to pass an ID from the server. This can be done through the data-id attribute of the root element. This is important, since each widget on the page may have different settings.

      To do this, return back to your top level plugin directory and open shortcode.php for editing:

      • cd ..
      • nano includes/shortcode.php

      Update it to have the following highlighted lines:

      /var/www/wordpress/wp-content/plugins/react-wordpress/includes/shortcode.php

      <?php
      // This file enqueues your shortcode.
      
      defined( 'ABSPATH' ) or die( 'Direct script access disallowed.' );
      
      add_shortcode( 'erw_widget', function( $atts ) {
        $default_atts = array( 'color' => 'black' );
        $args = shortcode_atts( $default_atts, $atts );
        $uniqid = uniqid('id');
      
        return "<div class='erw-root' data-id='{$uniqid}'></div>";
      });
      

      The first new line generates a unique ID with the prefix id. The updated line attaches the ID to the React root using the data-id attribute. This will make the ID accessible in React.

      Save the file, but do not yet exit from it.

      Write Settings to the JavaScript window Object

      In the shortcode file, you will write the settings to the page in a window-global JavaScript object. Using the window object ensures it can be accessed from within React.

      With shortcode.php still open, update it so it contains the following:

      /var/www/wordpress/wp-content/plugins/react-wordpress/includes/shortcode.php

      <?php
      // This file enqueues your shortcode.
      
      defined( 'ABSPATH' ) or die( 'Direct script access disallowed.' );
      
      add_shortcode( 'erw_widget', function( $atts ) {
        $default_atts = array( 'color' => 'black' );
        $args = shortcode_atts( $default_atts, $atts );
        $uniqid = uniqid('id');
      
        global $current_user;
        $display_name = $current_user ? $current_user->display_name : 'World';
      
        ob_start(); ?>
        <script>
        window.erwSettings = window.erwSettings || {};
        window.erwSettings["<?= $uniqid ?>"] = {
          'color': '<?= $args["color"] ?>',
          'name': '<?= $display_name ?>',
        }
        </script>
        <div class="erw-root" data-id="<?= $uniqid ?>"></div>
      
        <?php
        return ob_get_clean();
      });
      

      These updates write a <script> block before each element that initializes the window-global settings object and populates it with the data provided in WP Admin.

      Note: The syntax <?= is shorthand for <?php echo

      Save and quit the file.

      Now, inspect the WordPress page in your web browser. This will show you the HTML for your page. If you CTRL+F and search for window.erwSettings, you will see the settings being written to the HTML of your page as the following:

      …
        window.erwSettings = window.erwSettings || {};
        window.erwSettings["id5d5f1958aa5ae"] = {
          'color': '#cf6f1a',
          'name': 'sammy',
        }
      …
      

      Retrieve Settings From React

      In the React app, you will retrieve the settings based on the ID and pass the border color value to the App component as a property (prop). This lets the App component use the value without needing to know where it came from.

      Open index.js for editing:

      • sudo nano widget/src/index.js

      Update it so it contains the following highlighted lines:

      /var/www/wordpress/wp-content/plugins/react-wordpress/widget/src/index.js

      import React from 'react';
      import ReactDOM from 'react-dom';
      import './index.css';
      import * as serviceWorker from './serviceWorker';
      
      const App = ({ settings }) => (
        <div className="App" style={{borderColor: settings.color}}>
          <span className="App__Message">Hello,<br />{settings.name}!</span>
        </div>
      );
      
      const targets = document.querySelectorAll('.erw-root');
      Array.prototype.forEach.call(targets, target => {
        const id = target.dataset.id;
        const settings = window.erwSettingstag:www.digitalocean.com,2005:/community/tutorials/how-to-embed-a-react-application-in-wordpress-on-ubuntu-18-04;
        ReactDOM.render(<App settings={settings} />, target)
      });
      
      serviceWorker.unregister();
      

      Save the file and exit from your text editor.

      Your React app will now use the unique ID from the window-global window.erwSettings object to retrieve settings and pass them to the App component. To put this into effect, re-compile your application:

      • cd widget
      • sudo npm run build

      After completing this last step, refresh the WordPress page in your browser. You will see the user-provided border color and the server-provided display name appear in the widgets:

      Widgets with Settings Applied

      Conclusion

      In this tutorial, you created your own WordPress plugin with a React application inside of it. You then built a shortcode as a bridge to make your application embeddable within the WP Admin page builder, and in the end, you customized your widget on the page.

      Now, you can expand on your React application with the confidence that your delivery mechanism is already in place. This foundation in WordPress ensures that you can focus on the client-side experience, and as your application expands and grows, you can easily add more production-oriented tools and techniques that will work with any WordPress installation.

      For further reading on what you can do with your solid React foundation, try exploring one of these tutorials:



      Source link

      How To Install WordPress with a Managed Database on Ubuntu 18.04


      A previous version of this tutorial was written by Justin Ellingwood

      Introduction

      WordPress is the most popular CMS (content management system) on the internet. It’s a great choice for getting a website up and running quickly, and after the initial setup, almost all administration can be done through the web frontend.

      WordPress is designed to pull content – including posts, comments, user profiles, and other data – from a database backend. As a website grows and must satisfy more and more traffic, it can eventually outgrow its initial database. To resolve this, one can scale up their database by migrating their data to a machine with more RAM or CPU, but this is a tedious process that runs the risk of data loss or corruption. This is why some WordPress developers choose to build their websites on managed databases, which allow users to scale their database automatically with a far lower risk of data loss.

      In this guide, we’ll focus on setting up a WordPress instance with a managed MySQL database and an Ubuntu 18.04 server. This will require you to install PHP and Apache to serve the content over the web.

      Prerequisites

      In order to complete this tutorial, you will need:

      • Access to an Ubuntu 18.04 server: This server should have a non-root sudo-enabled user and a firewall configured. You can set this up by following our Ubuntu 18.04 initial server setup guide.
      • A managed MySQL database: To provision a Managed MySQL Database from DigitalOcean, see our Managed Databases product documentation. Note that this guide will refer to DigitalOcean Managed Databases in examples, but the instructions provided here should also generally work for managed MySQL databases from other cloud providers.
      • A LAMP stack installed on your server: In addition to a database, WordPress requires a web server and PHP to function correctly. Setting up a complete LAMP stack (Linux, Apache, MySQL, and PHP) fulfills all of these requirements. Follow this guide to install and configure this software. As you follow this guide, make sure that you set up a virtual host to point to a domain name that you own. Additionally, be sure to skip Step 2, as installing mysql-server on your machine will make your managed database instance redundant.
      • TLS/SSL security implemented for your site: If you have a domain name, the easiest way to secure your site is with Let’s Encrypt, which provides free, trusted certificates. Follow our Let’s Encrypt guide for Apache to set this up. Note that this will also require you to obtain a domain name and set up DNS records on your server. Follow this introduction to DigitalOcean DNS for details on how to configure this. Altneratively, if you don’t have a domain name, you use a self-signed certificate for your site.

      When you are finished with the setup steps, log into your server as your non-root user and continue below.

      Step 1 – Adding the MySQL Software Repository and Installing mysql-client

      In order to configure your managed MySQL instance, you will need to install a client that will allow you to access the database from your server. This step will walk you through the process of installing the mysql-client package.

      In many cases, you can just install mysql-client with the apt command, but if you’re using the default Ubuntu repositories this will install version 5.7 of the program. In order to access a DigitalOcean Managed MySQL database, you will need to install version 8.0 or above. To do so, you must first add the MySQL software repository before installing the package.

      Begin by navigating to the MySQL APT Repository page in your web browser. Find the Download button in the lower-right corner and click through to the next page. This page will prompt you to log in or sign up for an Oracle web account. You can skip that and instead look for the link that says No thanks, just start my download. Right-click the link and select Copy Link Address (this option may be worded differently, depending on your browser).

      Now you’re ready to download the file. On your server, move to a directory you can write to:

      Download the file using curl, remembering to paste the address you just copied in place of the highlighted portion of the following command. You also need to pass two command line flags to curl. -O instructs curl to output to a file instead of standard output. The L flag makes curl follow HTTP redirects, which is necessary in this case because the address you copied actually redirects to another location before the file downloads:

      • curl -OL https://dev.mysql.com/get/mysql-apt-config_0.8.13-1_all.deb

      The file should now be downloaded in your current directory. List the files to make sure:

      You will see the filename listed in the output:

      Output

      mysql-apt-config_0.8.13-1_all.deb . . .

      Now you can add the MySQL APT repository to your system's repository list. The dpkg command is used to install, remove, and inspect .deb software packages. The following command includes the -i flag, indicating that you'd like to install from the specified file:

      • sudo dpkg -i mysql-apt-config*

      During the installation, you'll be presented with a configuration screen where you can specify which version of MySQL you'd prefer, along with an option to install repositories for other MySQL-related tools. The defaults will add the repository information for the latest stable version of MySQL and nothing else. This is what we want, so use the down arrow to navigate to the Ok menu option and hit ENTER.

      Selecting mysql-apt-config configuration options

      Following that, the package will finish adding the repository. Refresh your apt package cache to make the new software packages available:

      Next, you can clean up your system a bit and delete the file you downloaded, as you won't need it in the future:

      Note: If you ever need to update the configuration of these repositories, just run the following command to select your new options:

      • sudo dpkg-reconfigure mysql-apt-config

      After selecting your new options, run the following command to refresh your package cache:

      Now that you've added the MySQL repositories, you're ready to install the actual MySQL client software. Do so with the following apt command:

      • sudo apt install mysql-client

      Once that command finishes, check the software version number to ensure that you have the latest release:

      Output

      mysql Ver 8.0.17-cluster for Linux on x86_64 (MySQL Community Server - GPL)

      You're now able to connect to your managed database and begin preparing it to function with WordPress.

      Step 2 – Creating a MySQL Database and User for WordPress

      WordPress uses MySQL to manage and store site and user information. Assuming you have completed all the prerequisite tutorials, you will have already provisioned a managed MySQL instance. Here, we'll take the preparatory step of creating a database and a user for WordPress to use.

      Most managed database providers provide a uniform resource identifier (URI) used for connecting to the database instance. If you're using a DigitalOcean Managed Database, you can find the relevant connection information in your Cloud Control Panel.

      First, click Databases in the left-hand sidebar menu and select the MySQL database you want to use for your WordPress installation. Scroll down to the Connection Details section and copy the link in the host field. Then paste this link into the following command, replacing host_uri with the information you just copied. Likewise, copy the port number in the port field – which will be 25060 on a DigitalOcean Managed Database – and replace port with that number. Additionally, if this is your first time connecting to your managed database and you've not created your own administrative MySQL user, copy the value in the username field and paste it into the command, replacing user:

      • mysql -u user -p -h host_uri -P port

      This command includes the -p flag, which will prompt you for the password of the MySQL user you specified. For a DigitalOcean Managed Database's default doadmin user, you can find this by clicking the show link in the Connection Details section to reveal the password. Copy and paste it into your terminal when prompted.

      Note: If you are not using a DigitalOcean Managed Database, your connection options may differ. If that's the case, you should consult your provider's documentation for instructions on connecting third party applications to your database.

      From the MySQL prompt, create a new database that WordPress will control. You can call this whatever you would like, but we will use the name wordpress in this guide to keep it simple. Create the database for WordPress by typing:

      • CREATE DATABASE wordpress DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;

      Note: Every MySQL statement must end in a semi-colon (;). Check to make sure this is present if you are running into any issues.

      Next, create a new MySQL user account that you will use exclusively to operate on the new database. Creating single-purpose databases and accounts is a good idea from a management and security standpoint. We will use the name wordpressuser in this guide, but feel free to change this if you'd like.

      Run the following command, but replace your_server_ip with your Ubuntu server's IP address. Be aware, though, that this will limit wordpressuser to only be able to connect from your LAMP server; if you plan to manage WordPress from your local computer, you should enter that machine's IP address instead. Additionally, choose a strong password for your database user:

      • CREATE USER 'wordpressuser'@your_server_ip IDENTIFIED WITH mysql_native_password BY 'password';

      Note: If you do not know what your server's public IP address is, there are a number of ways you can find it. Usually, this is the address you use to connect to your server through SSH.

      One method is to use the curl utility to contact an outside party to tell you how it sees your server. For example, you can use curl to contact an IP-checking tool like ICanHazIP:

      • curl http://icanhazip.com

      This command will return your server's public IP address in your output.

      Then grant this user access to the database you just created. Do so by running the following command:

      • GRANT ALL ON wordpress.* TO 'wordpressuser'@your_server_ip;

      You now have a database and user account, each made specifically for WordPress. Next, you need to flush the privileges so that the current MySQL session recognizes the changes you've made:

      Following that, exit out of MySQL by typing:

      That takes care of configuring your managed MySQL database to function with WordPress. In the next step, you will install a few PHP extensions in order to get more functionality out of the CMS.

      Step 3 – Installing Additional PHP Extensions

      Assuming you followed the prerequisite LAMP stack tutorial, you will have installed a few extensions intended to get PHP to properly communicate with MySQL. WordPress and many of its plugins leverage additional PHP extensions to add additional functionalities.

      To download and install some of the more popular PHP extensions for use with WordPress, run the following command:

      • sudo apt install php-curl php-gd php-mbstring php-xml php-xmlrpc php-soap php-intl php-zip

      Note: Each WordPress plugin has its own set of requirements. Some may require you to install additional PHP packages. Check your plugin documentation to see which extensions it requires. If they are available, they can be installed with apt as demonstrated above.

      You will restart Apache to load these new extensions in the next section. If you're returning here to install additional plugins, though, you can restart Apache now by typing:

      • sudo systemctl restart apache2

      Otherwise, continue on to Step 4.

      Step 4 – Adjusting Apache's Configuration to Allow for .htaccess Overrides and Rewrites

      In order for Apache to be able to properly serve your WordPress installation, you must make a few minor adjustments to your Apache configuration.

      If you followed the prerequisite tutorials, you should already have a configuration file for your site in the /etc/apache2/sites-available/ directory. We'll use /etc/apache2/sites-available/your_domain.conf as an example here, but you should substitute the path to your configuration file where appropriate.

      Additionally, we will use /var/www/your_domain as the root directory in this example WordPress install. You should use the web root specified in your own configuration.

      Note: It's possible you are using the 000-default.conf default configuration (with /var/www/html as your web root). This is fine to use if you're only going to host one website on this server. If not, it's best to split the necessary configuration into logical chunks, one file per site.

      Currently, the use of .htaccess files is disabled. WordPress and many WordPress plugins use these files extensively for in-directory tweaks to the web server's behavior.

      Open the Apache configuration file for your website:

      • sudo nano /etc/apache2/sites-available/your_domain.conf

      To allow .htaccess files, you need to set the AllowOverride directive within a Directory block pointing to your document root. Add the following block of text inside the VirtualHost block in your configuration file, being sure to use the correct web root directory:

      /etc/apache2/sites-available/your_domain.conf

      <Directory /var/www/your_domain>
          AllowOverride All
      </Directory>
      

      When you are finished, save and close the file.

      Next, enable mod_rewrite so that you can employ the WordPress permalink feature:

      Before implementing the changes you've just made, check to make sure there aren't any syntax errors in your configuration file:

      • sudo apache2ctl configtest

      The output might have a message that looks like this:

      Output

      AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to suppress this message Syntax OK

      If you wish to suppress the top line, just add a ServerName directive to your main (global) Apache configuration file at /etc/apache2/apache2.conf. The ServerName can be your server's domain or IP address. However, this is just a message; it doesn't affect the functionality of your site and as long as the output contains Syntax OK, you're all set to continue.

      Restart Apache to implement the changes:

      • sudo systemctl restart apache2

      With that, you're ready to download and set up WordPress itself.

      Step 5 – Downloading WordPress

      Now that your server software is configured, you can install and configure WordPress. For security reasons, it is always recommended to get the latest version of WordPress from their site.

      First, navigate to into a writable directory. /tmp will work for the purposes of this step:

      Then download the compressed release by typing:

      • curl -O https://wordpress.org/latest.tar.gz

      Extract the compressed file to create the WordPress directory structure:

      You will move these files into your document root momentarily. Before doing so, add a dummy .htaccess file so that this will be available for WordPress to use later.

      Create the file by typing:

      • touch /tmp/wordpress/.htaccess

      Also, copy over the sample configuration file to the filename that WordPress actually reads:

      • cp /tmp/wordpress/wp-config-sample.php /tmp/wordpress/wp-config.php

      Create an upgrade directory, so that WordPress won't run into permissions issues when trying to do this on its own following an update to its software:

      • mkdir /tmp/wordpress/wp-content/upgrade

      Then copy the entire contents of the directory into your document root. The following command uses a period at the end of the source directory to indicate that everything within the directory should be copied, including hidden files (like the .htaccess file you just created):

      • sudo cp -a /tmp/wordpress/. /var/www/your_domain

      That takes care of downloading WordPress onto your server. At this point, though, you still won't be able to access the WordPress setup interface in your browser. To fix that, you'll need to make a few changes to your server's WordPress configuration.

      Step 6 – Configuring the WordPress Directory

      Before going through the web-based WordPress setup, you need to adjust some items in your WordPress directory. One important configuration change involves setting up reasonable file permissions and ownership.

      Start by giving ownership of all the files to the www-data user and group. This is the user that the Apache web server runs as on Debian and Ubuntu systems, and Apache will need to be able to read and write WordPress files in order to serve the website and perform automatic updates.

      Update the ownership of your web root directory with chown:

      • sudo chown -R www-data:www-data /var/www/your_domain

      Next run the following two find commands to set the correct permissions on the WordPress directories and files:

      • sudo find /var/www/your_domain/ -type d -exec chmod 750 {} ;
      • sudo find /var/www/your_domain/ -type f -exec chmod 640 {} ;

      These should be a reasonable permissions set to start with. Be aware, though, that some plugins and procedures might require additional updates.

      Now, you need to make some changes to the main WordPress configuration file.

      When you open the file, the first order of business will be to replace some secret keys to provide security for your installation. WordPress provides a secure generator for these values so that you do not have to try to come up with good values on your own. These are only used internally, so it won't hurt usability to have complex, secure values here.

      To grab secure values from the WordPress secret key generator, run the following command:

      • curl -s https://api.wordpress.org/secret-key/1.1/salt/

      You will get back unique values that look something like this:

      Warning! It is important that you request unique values each time. Do NOT copy the values shown here!

      Output

      define('AUTH_KEY', '1jl/vqfs<XhdXoAPz9 DO NOT COPY THESE VALUES c_j{iwqD^<+c9.k<J@4H'); define('SECURE_AUTH_KEY', 'E2N-h2]Dcvp+aS/p7X DO NOT COPY THESE VALUES {Ka(f;rv?Pxf})CgLi-3'); define('LOGGED_IN_KEY', 'W(50,{W^,OPB%PB<JF DO NOT COPY THESE VALUES 2;y&,2m%3]R6DUth[;88'); define('NONCE_KEY', 'll,4UC)7ua+8<!4VM+ DO NOT COPY THESE VALUES #`DXF+[$atzM7 o^-C7g'); define('AUTH_SALT', 'koMrurzOA+|L_lG}kf DO NOT COPY THESE VALUES 07VC*Lj*lD&?3w!BT#-'); define('SECURE_AUTH_SALT', 'p32*p,]z%LZ+pAu:VY DO NOT COPY THESE VALUES C-?y+K0DK_+F|0h{!_xY'); define('LOGGED_IN_SALT', 'i^/G2W7!-1H2OQ+t$3 DO NOT COPY THESE VALUES t6**bRVFSD[Hi])-qS`|'); define('NONCE_SALT', 'Q6]U:K?j4L%Z]}h^q7 DO NOT COPY THESE VALUES 1% ^qUswWgn+6&xqHN&%');

      These are configuration lines that you can paste directly into your configuration file to set secure keys. Copy the output you received now.

      Then, open the WordPress configuration file:

      • sudo nano /var/www/your_domain/wp-config.php

      Find the section that contains the dummy values for those settings. It will look something like this:

      /var/www/your_domain/wp-config.php

      . . .
      
      define('AUTH_KEY',         'put your unique phrase here');
      define('SECURE_AUTH_KEY',  'put your unique phrase here');
      define('LOGGED_IN_KEY',    'put your unique phrase here');
      define('NONCE_KEY',        'put your unique phrase here');
      define('AUTH_SALT',        'put your unique phrase here');
      define('SECURE_AUTH_SALT', 'put your unique phrase here');
      define('LOGGED_IN_SALT',   'put your unique phrase here');
      define('NONCE_SALT',       'put your unique phrase here');
      
      . . .
      

      Delete those lines and paste in the values you copied from the command line:

      /var/www/your_domain/wp-config.php

      . . .
      
      define('AUTH_KEY',         'VALUES COPIED FROM THE COMMAND LINE');
      define('SECURE_AUTH_KEY',  'VALUES COPIED FROM THE COMMAND LINE');
      define('LOGGED_IN_KEY',    'VALUES COPIED FROM THE COMMAND LINE');
      define('NONCE_KEY',        'VALUES COPIED FROM THE COMMAND LINE');
      define('AUTH_SALT',        'VALUES COPIED FROM THE COMMAND LINE');
      define('SECURE_AUTH_SALT', 'VALUES COPIED FROM THE COMMAND LINE');
      define('LOGGED_IN_SALT',   'VALUES COPIED FROM THE COMMAND LINE');
      define('NONCE_SALT',       'VALUES COPIED FROM THE COMMAND LINE');
      
      . . .
      

      Next you need to modify some of the database connection settings at the beginning of the file. First, update the 'DB_NAME', 'DB_USER', and 'DB_PASSWORD' fields to point to the database name, database user, and the associated password that you configured within MySQL:

      /var/www/your_domain/wp-config.php

      . . .
      /** The name of the database for WordPress */
      define('DB_NAME', 'wordpress');
      
      /** MySQL database username */
      define('DB_USER', 'wordpressuser');
      
      /** MySQL database password */
      define('DB_PASSWORD', 'password');
      
      . . .
      

      You will also need to replace localhost in the 'DB_HOST' field with your managed database's host. Additionally, append a colon (:) and your database's port number to the host:

      /var/www/wordpress/wp-config.php

      . . .
      
      /** MySQL hostname */
      define( 'DB_HOST', 'managed_database_host:managed_database_port' );
      
      . . .
      

      The last change you need to make is to set the method that WordPress will use to write to the filesystem. Since you've already given the web server permission to write where it needs to, you can explicitly set the filesystem method to direct port. Failure to set this with your current settings would result in WordPress prompting for FTP credentials when you perform certain actions.

      This setting can be added below the database connection settings, or anywhere else in the file:

      /var/www/your_domain/wp-config.php

      . . .
      
      define('FS_METHOD', 'direct');
      . . .
      

      Save and close the file when you are finished.

      After making those changes, you're all set to finish the process of installing WordPress in your web browser. However, there's one more step that we recommend you complete to add an extra layer of security to your configuration.

      At this point, your WordPress installation is communicating with your managed MySQL database. However, there's no guarantee that data transfers between the two machines are secure. In this step, we will configure WordPress to communicate with your MySQL instance over a TLS/SSL connection to ensure secure communications between the two machines.

      To do so, you'll need your managed database's CA certificate. For a DigitalOcean Managed Database, you can find this by once again navigating to the Databases tab in your Control Panel. Click on your database, and find the Connection Details section. There will be a button there that reads Download the CA certificate. Click this button to download the certificate to your local machine.

      Then transfer this file to your WordPress server. If your local machine is running Linux or macOS, you can use a tool like scp:

      • scp /path/to/file/ca-certificate.crt sammy@your_server_ip:/tmp

      If your local machine is running Windows, you can use an alternative tool like WinSCP.

      Once the CA certificate is on your server, move it to the /user/local/share/ca-certificates/ directory, Ubuntu's trusted certificate store:

      • sudo mv /tmp/ca-certificate.crt /usr/local/share/ca-certificates/

      Following this, run the update-ca-certificates command. This program looks for certificates within /usr/local/share/ca-certificates, adds any new ones to the /etc/ssl/certs/ directory, and generates a list of trusted SSL certificates based on its contents:

      • sudo update-ca-certificates

      Then, reopen your wp-config.php file:

      • nano /var/www/your_domain/wp-config.php

      Somewhere in the file, add the following line:

      /var/www/your_domain/wp-config.php

      . . .
      define('MYSQL_CLIENT_FLAGS', MYSQLI_CLIENT_SSL);
      . . .
      

      Save and close the file.

      Following that, WordPress will securely communicate with your managed MySQL database.

      Step 8 – Completing the Installation Through the Web Interface

      Now that the server configuration is complete, you can complete the installation through the WordPress web interface.

      In your web browser, navigate to your server's domain name or public IP address:

      https://server_domain_or_IP
      

      Assuming there aren't any errors in your WordPress or Apache configurations, you'll see the WordPress language selection splash page. Select the language you would like to use:

      WordPress language selection

      After selecting your language, you will see the main setup page.

      Select a name for your WordPress site and choose a username (it is recommended not to choose something like "admin" for security purposes). A strong password is generated automatically. Save this password or enter an alternative strong password.

      Enter your email address and select whether you want to discourage search engines from indexing your site:

      WordPress setup installation

      When you click ahead, you will be taken to a page that prompts you to log in:

      WordPress login prompt

      Once you log in, you will be taken to the WordPress administration dashboard:

      WordPress login prompt

      From here, you can begin customizing your new WordPress site and start publishing content. If this is your first time using WordPress, we encourage you to explore the interface a bit to get acquainted with your new CMS.

      Conclusion

      By completing this guide, you will have WordPress installed and ready to use on your server. Additionally, your WordPress installation is dynamically pulling posts, pages, and other content from your managed MySQL database.

      Some common next steps are to choose the permalinks setting for your posts. This setting can be found under Settings > Permalinks. You could also select a new theme in Appearance > Themes. Once you start loading some content into your site, you could also configure a CDN to speed up your site's asset delivery.



      Source link

      How to Install WordPress with LAMP on Debian 10


      Introduction

      WordPress is the most popular CMS (content management system) on the internet. It allows you to easily set up flexible blogs and websites on top of a MariaDB backend with PHP processing. WordPress has seen incredible adoption and is a great choice for getting a website up and running quickly. After setup, almost all administration can be done through the web frontend.

      In this guide, we’ll focus on getting a WordPress instance set up on a LAMP stack (Linux, Apache, MariaDB, and PHP) on a Debian 10 server.

      Prerequisites

      In order to complete this tutorial, you will need access to a Debian 10 server.

      You will need to perform the following tasks before you can start this guide:

      • Create a sudo user on your server: We will be completing the steps in this guide using a non-root user with sudo privileges. You can create a user with sudo privileges by following our Debian 10 initial server setup guide.
      • Install a LAMP stack: WordPress will need a web server, a database, and PHP in order to correctly function. Setting up a LAMP stack (Linux, Apache, MariaDB, and PHP) fulfills all of these requirements. Follow this guide to install and configure this software.
      • Secure your site with SSL: WordPress serves dynamic content and handles user authentication and authorization. TLS/SSL is the technology that allows you to encrypt the traffic from your site so that your connection is secure. The way you set up SSL will depend on whether you have a domain name for your site.
        • If you have a domain name… the easiest way to secure your site is with Let’s Encrypt, which provides free, trusted certificates. Follow our Let’s Encrypt guide for Apache to set this up.
        • If you do not have a domain… and you are just using this configuration for testing or personal use, you can use a self-signed certificate instead. This provides the same type of encryption, but without the domain validation. Follow our self-signed SSL guide for Apache to get set up.

      When you are finished with the setup steps, log in to your server as your sudo user and continue below.

      Step 1 — Creating a MariaDB Database and User for WordPress

      The first step that we will take is a preparatory one. WordPress requires a MySQL-based database to store and manage site and user information. We have MariaDB — a drop-in replacement for MySQL — installed already, but we need to make a database and a user for WordPress to use.

      To get started, open up the MariaDB prompt as the root account:

      Note: If you set up another account with administrative privileges when you installed and set up MariaDB, you can also log in as that user. You’ll need to do so with the following command:

      After issuing this command, MariaDB will prompt you for the password you set for that account.

      Begin by creating a new database that WordPress will control. You can call this whatever you would like but, to keep it simple for this guide, we will name it wordpress.

      Create the database for WordPress by typing:

      • CREATE DATABASE wordpress DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;

      Note that every MySQL statement must end in a semi-colon (;). Check to make sure this is present if you are running into any issues.

      Next, create a separate MySQL user account that we will use exclusively to operate on our new database. Creating single-function databases and accounts is a good idea from a management and security standpoint. We will use the name wordpress_user in this guide, but feel free to change this if you'd like.

      Create this account, set a password, and grant the user access to the database you just created with the following command. Remember to choose a strong password for your database user:

      • GRANT ALL ON wordpress.* TO 'wordpress_user'@'localhost' IDENTIFIED BY 'password';

      You now have a database and user account, each made specifically for WordPress. Run the following command to reload the grant tables so that the current instance of MariaDB knows about the changes you've made:

      Exit out of MariaDB by typing:

      Now that you’ve configured the database and user that will be used by WordPress, you can move on to installing some PHP-related packages used by the CMS.

      Step 2 — Installing Additional PHP Extensions

      When setting up our LAMP stack, we only required a very minimal set of extensions in order to get PHP to communicate with MariaDB. WordPress and many of its plugins leverage additional PHP extensions.

      Download and install some of the most popular PHP extensions for use with WordPress by typing:

      • sudo apt update
      • sudo apt install php-curl php-gd php-mbstring php-xml php-xmlrpc php-soap php-intl php-zip

      Note: Each WordPress plugin has its own set of requirements. Some may require additional PHP packages to be installed. Check your plugin documentation to find its PHP requirements. If they are available, they can be installed with apt as demonstrated above.

      We will restart Apache to load these new extensions in the next section. If you are returning here to install additional plugins, you can restart Apache now by typing:

      • sudo systemctl restart apache2

      At this point, all that’s left to do before installing WordPress is to make some changes to your Apache configuration in order to allow the CMS to function smoothly.

      Step 3 — Adjusting Apache's Configuration to Allow for .htaccess Overrides and Rewrites

      With the additional PHP extensions installed and ready for use, the next thing to do is to make a few changes to your Apache configuration. Based on the prerequisite tutorials, you should have a configuration file for your site in the /etc/apache2/sites-available/ directory. We'll use /etc/apache2/sites-available/wordpress.conf as an example here, but you should substitute the path to your configuration file where appropriate.

      Additionally, we will use /var/www/wordpress as the root directory of our WordPress install. You should use the web root specified in your own configuration.

      Note: It's possible you are using the 000-default.conf default configuration (with /var/www/html as your web root). This is fine to use if you're only going to host one website on this server. If not, it's best to split the necessary configuration into logical chunks, one file per site.

      Currently, the use of .htaccess files is disabled. WordPress and many WordPress plugins use these files extensively for in-directory tweaks to the web server's behavior.

      Open the Apache configuration file for your website. Note that if you have an existing Apache configuration file for your website, this file’s name will be different:

      • sudo nano /etc/apache2/sites-available/wordpress.conf

      To allow .htaccess files, you’ll need to add a Directory block pointing to your document root with an AllowOverride directive within it. Add the following block of text inside the VirtualHost block in your configuration file, being sure to use the correct web root directory:

      /etc/apache2/sites-available/wordpress.conf

      <Directory /var/www/wordpress/>
          AllowOverride All
      </Directory>
      

      When you are finished, save and close the file.

      Next, enable the rewrite module in order to utilize the WordPress permalink feature:

      Before implementing the changes you've made, check to make sure that you haven't made any syntax errors:

      • sudo apache2ctl configtest

      If your configuration file’s syntax is correct, you’ll see the following in your output:

      Output

      Syntax OK

      If this command reports any errors, go back and check that you haven’t made any syntax errors in your configuration file. Otherwise, restart Apache to implement the changes:

      • sudo systemctl restart apache2

      Next, we will download and set up WordPress itself.

      Step 4 — Downloading WordPress

      Now that your server software is configured, you can download and set up WordPress. For security reasons in particular, it is always recommended to get the latest version of WordPress directly from their site.

      Note: We will use curl to download WordPress, but this program may not be installed by default on your Debian server. To install it, run:

      Change into a writable directory and then download the compressed release by typing:

      • cd /tmp
      • curl -O https://wordpress.org/latest.tar.gz

      Extract the compressed file to create the WordPress directory structure:

      We will move these files into our document root momentarily. Before we do, though, add a dummy .htaccess file so that this will be available for WordPress to use later.

      Create the file by typing:

      • touch /tmp/wordpress/.htaccess

      Then copy over the sample configuration file to the filename that WordPress actually reads:

      • cp /tmp/wordpress/wp-config-sample.php /tmp/wordpress/wp-config.php

      Additionally, create the upgrade directory so that WordPress won't run into permissions issues when trying to do this on its own following an update to its software:

      • mkdir /tmp/wordpress/wp-content/upgrade

      Then, copy the entire contents of the directory into your document root. Notice that the following command includes a dot at the end of the source directory to indicate that everything within the directory should be copied, including hidden files (like the .htaccess file you created):

      • sudo cp -a /tmp/wordpress/. /var/www/wordpress

      With that, you’ve successfully installed WordPress onto your web server and performed some of the initial configuration steps. Next, we’ll discuss some further configuration changes that will give WordPress the privileges it needs to function as well as access to the MariaDB database and user account you created previously.

      Step 5 — Configuring the WordPress Directory

      Before we can go through the web-based setup process for WordPress, we need to adjust some items in our WordPress directory.

      Start by giving ownership of all the files to the www-data user and group. This is the user that the Apache web server runs as, and Apache will need to be able to read and write WordPress files in order to serve the website and perform automatic updates.

      Update the ownership with chown:

      • sudo chown -R www-data:www-data /var/www/wordpress

      Next we will run two find commands to set the correct permissions on the WordPress directories and files:

      • sudo find /var/www/wordpress/ -type d -exec chmod 750 {} ;
      • sudo find /var/www/wordpress/ -type f -exec chmod 640 {} ;

      These should be a reasonable permissions set to start with, although some plugins and procedures might require additional tweaks.

      Following this, you will need to make some changes to the main WordPress configuration file.

      When you open the file, your first objective will be to adjust some secret keys to provide some security for your installation. WordPress provides a secure generator for these values so that you do not have to try to come up with good values on your own. These are only used internally, so it won't hurt usability to have complex, secure values here.

      To grab secure values from the WordPress secret key generator, type:

      • curl -s https://api.wordpress.org/secret-key/1.1/salt/

      You will get back unique values that look something like this:

      Warning! It is important that you request unique values each time. Do NOT copy the values shown below!

      Output

      define('AUTH_KEY', '1jl/vqfs<XhdXoAPz9 DO NOT COPY THESE VALUES c_j{iwqD^<+c9.k<J@4H'); define('SECURE_AUTH_KEY', 'E2N-h2]Dcvp+aS/p7X DO NOT COPY THESE VALUES {Ka(f;rv?Pxf})CgLi-3'); define('LOGGED_IN_KEY', 'W(50,{W^,OPB%PB<JF DO NOT COPY THESE VALUES 2;y&,2m%3]R6DUth[;88'); define('NONCE_KEY', 'll,4UC)7ua+8<!4VM+ DO NOT COPY THESE VALUES #`DXF+[$atzM7 o^-C7g'); define('AUTH_SALT', 'koMrurzOA+|L_lG}kf DO NOT COPY THESE VALUES 07VC*Lj*lD&?3w!BT#-'); define('SECURE_AUTH_SALT', 'p32*p,]z%LZ+pAu:VY DO NOT COPY THESE VALUES C-?y+K0DK_+F|0h{!_xY'); define('LOGGED_IN_SALT', 'i^/G2W7!-1H2OQ+t$3 DO NOT COPY THESE VALUES t6**bRVFSD[Hi])-qS`|'); define('NONCE_SALT', 'Q6]U:K?j4L%Z]}h^q7 DO NOT COPY THESE VALUES 1% ^qUswWgn+6&xqHN&%');

      These are configuration lines that you will paste directly into your configuration file to set secure keys. Copy the output you received to your clipboard, and then open the WordPress configuration file located in your document root:

      • sudo nano /var/www/wordpress/wp-config.php

      Find the section that contains the dummy values for those settings. It will look something like this:

      /var/www/wordpress/wp-config.php

      . . .
      
      define('AUTH_KEY',         'put your unique phrase here');
      define('SECURE_AUTH_KEY',  'put your unique phrase here');
      define('LOGGED_IN_KEY',    'put your unique phrase here');
      define('NONCE_KEY',        'put your unique phrase here');
      define('AUTH_SALT',        'put your unique phrase here');
      define('SECURE_AUTH_SALT', 'put your unique phrase here');
      define('LOGGED_IN_SALT',   'put your unique phrase here');
      define('NONCE_SALT',       'put your unique phrase here');
      
      . . .
      

      Delete these lines and paste in the values you copied from the command line:

      /var/www/wordpress/wp-config.php

      . . .
      
      define('AUTH_KEY',         'VALUES COPIED FROM THE COMMAND LINE');
      define('SECURE_AUTH_KEY',  'VALUES COPIED FROM THE COMMAND LINE');
      define('LOGGED_IN_KEY',    'VALUES COPIED FROM THE COMMAND LINE');
      define('NONCE_KEY',        'VALUES COPIED FROM THE COMMAND LINE');
      define('AUTH_SALT',        'VALUES COPIED FROM THE COMMAND LINE');
      define('SECURE_AUTH_SALT', 'VALUES COPIED FROM THE COMMAND LINE');
      define('LOGGED_IN_SALT',   'VALUES COPIED FROM THE COMMAND LINE');
      define('NONCE_SALT',       'VALUES COPIED FROM THE COMMAND LINE');
      
      . . .
      

      Next, modify the database connection settings at the top of the file. You need to adjust the database name, the database user, and the associated password that you’ve configured within MariaDB.

      The other change you must make is to set the method that WordPress should use to write to the filesystem. Since we've given the web server permission to write where it needs to, we can explicitly set the filesystem method to "direct". Failure to set this with our current settings would result in WordPress prompting for FTP credentials when you perform certain actions.

      This setting can be added below the database connection settings, or anywhere else in the file:

      /var/www/wordpress/wp-config.php

      . . .
      
      define('DB_NAME', 'wordpress');
      
      /** MySQL database username */
      define('DB_USER', 'wordpress_user');
      
      /** MySQL database password */
      define('DB_PASSWORD', 'password');
      
      . . .
      
      define('FS_METHOD', 'direct');
      

      Save and close the file when you are finished. Finally, you can finish installing and configuring WordPress by accessing it through your web browser.

      Step 6 — Completing the Installation Through the Web Interface

      Now that the server configuration is complete, we can complete the installation through the web interface.

      In your web browser, navigate to your server's domain name or public IP address:

      https://server_domain_or_IP
      

      Select the language you would like to use:

      WordPress language selection

      Next, you will come to the main setup page. Select a name for your WordPress site and choose a username (it is recommended not to choose something like "admin" for security purposes). A strong password is generated automatically. Save this password or select an alternative strong password.

      Enter your email address and select whether you want to discourage search engines from indexing your site:

      WordPress setup installation

      When ready, click the Install WordPress button. You’ll be taken to a page that prompts you to log in:

      WordPress login prompt

      Once you log in, you will be taken to the WordPress administration dashboard:

      WordPress login prompt

      From the dashboard, you can begin making changes to your site’s theme and publishing content.

      Conclusion

      WordPress should be installed and ready to use! Some common next steps are to choose the permalinks setting for your posts (can be found in Settings > Permalinks) or to select a new theme (in Appearance > Themes). If this is your first time using WordPress, explore the interface a bit to get acquainted with your new CMS, or check the First Steps with WordPress guide on their official documentation.



      Source link