How to Design A WordPress website using API (r)

Jul 22, 2023

Share this on

It is a live demonstration of the web-based site builders application.

Site builder application
App for building websites.

The API is Learning API

To generate an API key. API key. API key

  1. Log into Your My Dashboard.
  2. Visit your API Keys page ( Your name > Corporate settings >>then API Keys).
  3. Click to create an API Key.
  4. Choose an expiration date, or choose a date for the beginning along with the number of hours it will take for the key to use until.
  5. Check that the key is given a the same name.
  6. Click Here for Generate.
Create API Key on My
Create API Keys using My.

The process of building a WordPress site is done using the API

Once you've established that your API key is in place and you've received the API key, you can make the WordPress site with the API. In order to do that, you must use the site's /sites connection. The payload should be which contains these details:

  • business: It is a parameter that requires a identification number unique for the business which is found in the My Settings. It lets you know what is the name of the business is that has been linked to WordPress. WordPress website.
  • install_mode: This setting defines the kind of WordPress installation. The default setting is "plain," which sets the default WordPress website. There are other options to choose from such as "new" for a brand fresh WordPress installation and various others based on the specific needs of your.
  • is_subdomain_multisite: This boolean (true/false) parameter specifies whether the WordPress site should be configured as a multisite using subdomains.
  • admin_email The parameter is based from the email address of the WordPress administrator. This is utilized to handle administration tasks, and to be notified of important emails.
  • admin_password This parameter could be employed to generate usernames and passwords to the WordPress administrator account. Use a safe password to safeguard your website.
  • admin_user This parameter specifies an admin username that is associated with the WordPress administrator account. This is the username that is used to log in to the WordPress dashboard as well as to control the site.
  • is_multisite: Similar to is_subdomain_multisite, this boolean parameter determines whether the WordPress site should be configured as a multisite.
  • site_title It is a parameter which determines the title of your WordPress website. It appears at the top of every page of the site. It's possible to alter the display at any time.
  • Woocommerce This parameter will tell you if or not you'd like to enable the WooCommerce plugin in the process of creating your WordPress site design.
  • WP_language The parameter is a value in a string that represents the location or the language used by your WordPress site (discover the location of the locale of your WordPress localization in this article).

Once you have a better grasp of the parameters. This is an example what the payload which you submit to the API API. API API can appear like:

 "company": "54fb80af-576c-4fdc-ba4f-b596c83f15a1", "display_name": "First site", "region": "us-central1", "install_mode": "new", "is_subdomain_multisite": false, "admin_email": "[email protected]", "admin_password": "vJnFnN-~v)PxF[6k", "admin_user": "admin", "is_multisite": false, "site_title": "My First Site", "woocommerce": false, "wordpressseo": false, "wp_language": "en_US" 
const createWPSite = async () => const resp = await fetch( `https://api..com/v2/sites`, method: 'POST', headers: 'Content-Type': 'application/json', Authorization: 'Bearer ' , body: JSON.stringify( company: '54fb80af-576c-4fdc-ba4f-b596c83f15a1', display_name: 'First site', region: 'us-central1', install_mode: 'new', is_subdomain_multisite: false, admin_email: '[email protected]', admin_password: 'vJnFnN-~v)PxF[6k', admin_user: 'admin', is_multisite: false, site_title: 'My First Site', woocommerce: false, wordpressseo: false, wp_language: 'en_US' ) ); const data = await resp.json(); console.log(data); 

The code uses the JavaScript Fetch API. JavaScript Fetch API to send the HTTP POST request to API for making a WordPress site. The CreateWPSite function manages the entire process. In the function, the fetch request is made via the API's web site endpoint along with the details needed.

The data is then parsed into JSON with the help of resp.json() which is logged to the console. Be sure to replace the value YOUR_KEY_HERE with your API key. Change the value of your payload depending on the need. After that, you use this function CreateWPSite() to create the WordPress website using API.

The answer is:

 "operation_id": "sites:add-54fb80af-576c-4fdc-ba4f-b596c83f15a1", "message": "Adding site in progress", "status": 202 

Monitoring Operational Activities using the API

If you are beginning a new site development with the API it's essential to keep track of the performance of your business. It's possible to do this using a programming approach without the need to confirm the authenticity of your API making use of the API's operations connection.

In order to monitor the operation, you can use to monitor operations, use to observe operations, you can use your operation_id which you receive when you start any operation, for example, creating WordPress. WordPress website. Send the the operation_id to the operation's terminus as at the operations terminus.

const operationId = 'YOUR_operation_id_PARAMETER'; const resp = await fetch( `https://api..com/v2/operations/$operationId`, method: 'GET', headers: Authorization: 'Bearer ' ); const data = await resp.json(); console.log(data);

If the data response receives through the API The data response is then recorded on the console. The information provided by the response are valuable regarding the progress and status of the work. If, for example, the WordPress web-based site creation process is being completed it will look similar to this:

"status":"status" "message": "Operation in progress", "data": null

As with the previous method, when the procedure is successfully completed This is the result:

"message": "Successfully finished request", "status": 200, "data": null

WordPress API allows you to build a website. WordPress API allows you to develop an WordPress website and then examine its performance using the API. In order to further improve it, we may improve its functionality and develop an individual Interface for Users Interface (UI) capable to manage these procedures. So, even those not technical experts are able to take advantage of the API's features.

The development of a React application to Make a WordPress Website using API

Prerequisite

Getting Started

For a simpler project set-up procedure, a basic project is available for you to download. Begin by following these steps to get going:

2. Set up the repository on your local computer, and switch it over to the starting-files branch with the command below:

Git Checkout starter-files

3. Install all the dependencies required by using this command to install the NPM package. When the installation process is done, you can start local on your personal computer with the command npm run start. This opens the project at http://localhost:3000/.

Site builder form
Site builder form.

Understanding the Project Files

In the directory src in this project are two main subfolders: components and Pages. The folder that contains components includes reused components, such as pages, like those that have the header footer as well as footer which are utilized in both the Homepage as well as the details pages.

This project's primary focus is to implement the logic that is in the homepage page as well as the pages for details since the layout and navigation has already been put in place.

The Home page includes a form which gathers data from a range of fields. These are sent through the API. The result of the page is saved in the localStorage (you might consider other methods to save the operation ID that is essential to check the status of your process).

In the Detail page in the Detail page where the ID of operation is pulled from loaclStoage, which is then transferred to the API's /operation endpoint. This can be used to determine where the operation is in. This application includes a button that permits users to check the status on a periodic interval (you might make use of setInterval method to automate this process). setInterval method to automate the process).

Site builder operation information
Site builder details about operations.

Connecting to the API in React

The user interface (UI) is implemented It is now time to process the form submission on your website and to send a POST request via the API's http://sites endpoint. The request includes the details of the form in the payload. This makes it possible to develop the WordPress website.

In order to connect with the API, you'll need the business ID along with the API code. Once you've gotten the necessary credentials, try to store these in a safe environment variable inside the React application.

To set your environment variables, create the .env document within the directory that contains the root of your project. In this file, you can add the following lines:

REACT_APP__COMPANY_ID = 'YOUR_COMPANY_ID' REACT_APP__API_KEY = 'YOUR_API_KEY'

To access these environment variables within your project, you can use the syntax process.env.THE_VARIABLE. For example, to access the REACT_APP__COMPANY_ID, you would use process.env.REACT_APP__COMPANY_ID.

React's ability to retrieve form data with React

Within Home.jsx Home.jsx file there is an application type form. It is essential to include an algorithm on the form to collect the data, and then verify that it has been completed. To retrieve the information from the form in the React application, it is possible to employ the control component method and hook. This method lets you create an instance for each field, and then update the state when people input information.

It is then necessary to add to the useState hook which is found at the top within the file.

uses React as a base and utilizeState for "react'

Create an instance of a state variable for every form field in the functional component. In this case, for instance when there's an input field meant to be "Site title" You can then create the state variable siteTitle:

const[siteTitle] setSiteTitle[] ="useState" ('');

In this case, the siteTitle will represent the value of a state variable that contains the information in"Site title" input field "Site title" input field. setSiteTitle is the function that updates state variables.

In order to bind field fields to forms using an appropriate state value, include an appropriate state value as well as the onChange attributes for each input element. For example, in"Site title" input field "Site title" input field:

 setSiteTitle(event.target.value) />

In this this example it's that the attributes attribute is set in accordance with the websiteTitle state variable. It ensures that the input is displayed with the most current values of the website's title. In the event that OnChange happens, it will trigger the changes event handler is set to utilize this setting of the title function. The update of the title of the site status will display the latest value each time an user enters data in the input box.

This method is applicable to every field of the form, you will be able to build the needed state variables and modify them as users interact with the forms. This allows you to quickly access the data entered once you have submitted the form and perform the necessary actions or check the information on the form.

When you complete this procedure for every field in your form, Your Home.jsx file looks as follows:

import Header from '../components/Header'; import Footer from '../components/Footer'; const Home = () => return ( className="title">Site Builder with API className="description"> This is a React app that uses the API to create WordPress sites, without needing to access My dashboard. The form's input is displayed as a form-container input and the name is utilized to distinguish the website. Only used in My and temporary domain className='error-message'>Ensure this has more than 4 characters WordPress site title Appears across the top of every page of the site. It is possible to change it at a later time. className='error-message'>Ensure this has more than 4 characters WordPress admin username WordPress admin email className='error-message'>Ensure this is a valid email WordPress admin password Ensure you remember this password as it is what you'll use to log into WP-admin Data center location Allows you to place your website in a geographical location closest to your visitors. value=""> /* add options */ Install WooCommerce Install Yoast SEO className='btn'>Create Site ) export default Home; Implementing Form Field Validation Using useRef Hook To enable validation of form fields in React it is possible to take these steps. Concentrate on creating validation for fields similar to those found within the "Display name" as well as the "WordPress Administrator Email" fields. Beginning, you need to build references by hooks that determine how warning messages are displayed. Import useRef hook into the UseRef hook and generate references for each field: import useRef' from'react';displayNameRef const = useRef(null) Const wpEmailRef = useRef(null); After that, you attach these refs to element of error messages in the form fields. For example, for"Display Name" for instance, for the "Display Name" field, the ref is added to the span of tags. You'll see the error message, Name of Display. It helps you identify the web page. Only used in My and temporary domain setDisplayName(e.target.value) /> Ensure this has more than 4 characters The same applies to the "WordPress admin email" field: WordPress admin email setWpAdminEmail(e.target.value) /> className='error-message' ref=wpEmailRef>Ensure this is a valid email Now, we can design validation methods which check input values and decide whether to display the error messages. These are the functions that can be used to use for "Display name" and "WordPress admin email": const checkDisplayName = () => if (displayName.length let regex = /^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w2,3)+$/; if (!wpAdminEmail.match(regex)) wpEmailRef.current.style.display = 'block'; else wpEmailRef.current.style.display = 'none'; The functions are invoked at the time that the relevant input fields change. They check the value of input to validate the values as well as change the display of error messages using the style.display property of the error message's components. Formula for creating websites that has been validated. You can add more validations, or modify the validation process to suit your needs. Responding to Form Submission in React To control the event of submitting forms in the course to create the website We will have to do a few aspects. First, we add an onSubmit event handler for our form element. Inside the createSite function, we prevent the default form submission behavior by calling event.preventDefault(). This allows us to manage the process of sending forms using a programming approach. To ensure that the data on the form is correct before sending out the procedure of submission, it's necessary to confirm the methods CheckDisplayName along with checkWpAdminEmail. This ensures that fields are in line with the criteria specified. CreateSite = (e) = e.preventDefault(); checkDisplayName() and checkWpAdminEmail(); // Other logic ; When all validations have been performed and all fields required contain valid data and you have cleared localStorage, then proceed to clear it and make sure that there is an uncluttered environment that can be used to store the API response as well as the display name. Then, you'll be able to make an API request via the API using the fetch method. The request is a POST method to the https://api..com/v2/sites endpoint. It is important to provide all headers that are relevant as well as the payload in JSON. const createSiteWithAPI = async () => const resp = await fetch( `$APIUrl/sites`, method: 'POST', headers: 'Content-Type': 'application/json', Authorization: `Bearer $process.env.REACT_APP__API_KEY` , body: JSON.stringify( company: `$process.env.REACT_APP__COMPANY_ID`, display_name: displayName, region: centerLocation, install_mode: 'new', is_subdomain_multisite: false, admin_email: wpAdminEmail, admin_password: wpAdminPassword, admin_user: wpAdminUsername, is_multisite: false, site_title: siteTitle, woocommerce: false, wordpressseo: false, wp_language: 'en_US' ) ); // Handle the response data ; The payload is comprised of various information fields that the API requires, such as your company's ID, display name, region configuration mode, admin email, admin password etc. The values come from the respective state variables. Following the API request, we will wait for the response with await resp.json() in order to take the data relevant in the context of our request. We create a new object newData, with the operation ID and display name, which is then stored in the localStorage using localStorage.setItem. const createSiteWithAPI = async () => const resp = await fetch( // Fetch request here ); const data = await resp.json(); let newData = operationId: data.operation_id, display_name: displayName ; localStorage.setItem('state', JSON.stringify(newData)); navigate('/details'); In the end, we use the createSiteWithAPI function to ensure that, when users fill out the form and clicks the button to create a WordPress website is built with the help of API. Additionally, in the code, we mention that visitors are directed to the details.jsx page, which keeps on track of the events taking use of the API. To enable the navigation function to be used, it is necessary to set up UseNavigate into react-router.dom and set the configuration. Note: You can locate the entire source code of this page in the GitHub repository. The implementation of Operation Status Check with the API to determine the status of an operation using the API using the ID of the operation that was stored in the localStorage. This operation ID is retrieved from the localStorage using JSON.parse(localStorage.getItem('state')) and assigned to a variable. To check the operation status, make another API request to the API by sending a GET request to the /operations/operationId endpoint. This request will include the necessary headers like the Authorization header which includes the API Key. const [operationData, setOperationData] = useState( message: "Operation in progress" ); const APIUrl = 'https://api..com/v2'; const stateData = JSON.parse(localStorage.getItem('state')); const checkOperation = async () => const operationId = stateData.operationId; const resp = await fetch( `$APIUrl/operations/$operationId`, method: 'GET', headers: Authorization: `Bearer $process.env.REACT_APP__API_KEY` ); const data = await resp.json(); setOperationData(data); Once we receive an answer, we extract all relevant information from the response by using await resp.json(). The operation data is then updated in the state using setOperationData(data). In the return statement of the component, we display the operation message using operationData.message. We also provide an option that enables users to make a verification of the process by utilizing the operation check. Additionally, if the operational status is that it has successfully finished then users are able to take advantage of the hyperlinks that connection to WordPress administrators as well as the site's. The links are constructed using the stateData.display_name obtained from localStorage. Open WordPress admin Open WordPress admin URL opening URL Open WordPress admin URL opening URL Open WordPress admin Open URL Clicking on these links opens the WordPress admin page and site URL as well as the website URL in a separate tab. This allows you to open the site directly, without needing to go to My. This allows you to create your own WordPress website with ease using an application that is designed specifically to meet your requirements. How do you deploy your React-Based Software To enable your repository to create an account, follow these steps: or login to your account on My dashboard. On the left sidebar, in the right-hand sidebar click "Applications" followed by "Add services". Choose "Application" from the dropdown menus to install the React application onto . A window that has a modal menu that opens up select the repository you wish to create. If you have multiple branches, then you'll be able to choose which branch you wish to set up and give an application name. Choose one location for the data center of the choices available. The system will recognize the starting command of your application. Set up the environment variables of My before you deploy. After you've completed the installation of your application, you can begin the deployment process, which usually takes around a couple of minutes. A successful deployment generates a link to your application, like https://site-builder-ndg9i..app/. Summary In this video you've learnt how make use of the API to build the basis of a WordPress site and integrate the API into the React application. Be sure to make sure that you secure your API keys with a secured. If you believe you've made it available to the public, remove the keys, then make a new one. Which are the possible endpoints you'd like to see included in the API in the coming years? What do you want to see us develop through the API? Tell us via the comments.

This article was originally posted this site.

Article was posted on here