WordPress Archives - AYALR https://ayalr.com/category/programming/wordpress/ Tue, 30 Apr 2024 05:40:49 +0000 en-US hourly 1 https://wordpress.org/?v=6.0.3 https://ayalr.com/wp-content/uploads/2024/02/cropped-android-chrome-512x512-1-32x32.png WordPress Archives - AYALR https://ayalr.com/category/programming/wordpress/ 32 32 How to Backup a WordPress Site for free! https://ayalr.com/how-to-backup-wordpress-site-without-plugin/ Sun, 26 Dec 2021 12:36:39 +0000 https://ayalr.com/?p=315 1. Overview How to backup a WordPress Site free? The task is not trivial but I make it easier to keep your WordPress site safely backed up on your computer? I’m assuming that WordPress is installed on a Linux machine. However, this can be easily adapted to do it on other operating systems as well! …

How to Backup a WordPress Site for free! Read More »

The post How to Backup a WordPress Site for free! appeared first on AYALR.

]]>
1. Overview

How to backup a WordPress Site free? The task is not trivial but I make it easier to keep your WordPress site safely backed up on your computer? I’m assuming that WordPress is installed on a Linux machine. However, this can be easily adapted to do it on other operating systems as well!

2. Is there a plugin?

Why don’t you use an off the shelf plugin which has already been tried and tested?

This is a very legitimate question. There are many popular plugins out there such as UpdraftPlus WordPress Backup Plugin and Jetpack by WordPress.com just to name a few.

Don’t get me wrong, plugins are useful for a variety of reasons, but they have to be treated for what they are, third-party software, over which you have little or no control. From a security point of view, the fewer plugins you install, the better it is.

Furthermore, the more plugins you install, the slower the site will run. You might also be tempted to install a long list of plugins, causing incompatibilities over time.

2.1 How to backup wordpress site without plugin

If you have good knowledge of how WordPress works under the hood, you have good SQL and MySQL knowledge, and you can find your way around an operating system easily, then you will soon know how to backup a wordpress site without plugin.

3. What items are we backing up?

The best way to backup a wordpress site without plugin is to copy the:

  1. file system
  2. database schema

3.1 How to backup the File System

The first step is backing up the WordPress files from the file system, including scripts, themes, plugins, and uploaded content. You need to know the directory which holds all of your WordPress. In this case, the directory is:

/var/www/html

The following command will compress all contents from that location into one single file.

tar -cjf blogFiles_28-04-2019.tar /var/www/html

Let’s tackle that command piece by piece. “tar -cfj” is a Linux command with which we instruct the operating system to compress files it finds in the location “/var/www/html”, and name the result blogFiles_28-04-2019.tar”. Note that the data was inserted in a way to indicate when the backup was taken.

So, just go to a directory of your choice and execute that command. Once it finishes, you will be able to see a new file called “blogFiles_28-04-2019.tar“. The amount of time required by the command, and the file size of its result, depend on how large your WordPress site is. 

3.2 How to Backup WordPress Database Schema

It’s now time to get a copy of the database.

For this step, you will need:

  1. the username,
  2. the password,
  3. the database name,
  4. the hostname of your WordPress database.

If you don’t know this information but have access to your host, you can retrieve them by reading the contents of the wp-config.php file. In our setup, this file is found in /var/www/html/wp-config.php.

With all the information at hand, you can execute the following command, replacing the placeholders with your information:

mysqldump --user=[YOUR_USER] --password=[YOUR_PASSWORD] --databases [YOR_DB_NAME] --host=<YOUR_HOSTNAME> > blogData_28-04-2019.sql

By executing this command, we are instructing the database engine to take a copy of all WordPress database contents into the file blogData_28-04-2019.sql

4. Storing the backups

At this point, we have our WordPress site backed up into two files “blogFiles_28-04-2019.tar” and “blogData_28-04-2019.sql”.

For obvious reasons, keeping the backup files on the same and single server is not a bright idea. Should something happen to the server, the site will be lost, together with the backup files. We don’t want this to happen, hence there are a few more steps to complete. We need to store a copy of these files in a reliable and secure place.

In this article, I will describe two ways which are both reliable and secure. Apart from these mentioned, there are other solutions.

4.1 FTP

FTP stands for File Transfer Protocol and is used to move files from one server to another. There are applications like FileZilla, or the linux command line tool lftp. In this article, we’ll use the latter. Just in case the lftp is not installed by default on your server, you can install it using the following command:

sudo apt-get install lftp

Once lftp is present, you can execute the following to copy the two files created in the steps before.

lftp [YOUR_FTP_USERNAME]@[YOUR_FTP_HOSTNAME]:~> put blogData_28-04-2019.sql
lftp [YOUR_FTP_USERNAME]@[YOUR_FTP_HOSTNAME]:~> put blogFiles_28-04-2019.tar

In both cases, lftp will ask for the password

4.2 The Cloud

Another alternative to using FTP servers is to use a cloud-based file storage solution like Google Drive, or DropBox. One solution would be more ideal than others depending on price plans and operating system support. There are other options too, like using a cloud-based source control solution like http://www.bitbucket.org, or http://www.github.com

5. Automation

In a real-world scenario, backups are automated. One approach that will be explained in this article is the following. In this part of the article, we will assume that you are hosting your blog on a Linux machine and that you are familiar with GIT.

We can achieve this by creating a shell script combining all the above steps and use a scheduler to execute our script at particular intervals. One such scheduler is the Linux Crontab. In this example, we will have the WordPress site backed up every day.

First, we need a shell script to create and upload the backup files. For simplicity’s sake, we will use bitbucket to store our backups on the cloud. We will also assume that the ssh keys of the client are already set in bitbucket. Create a new repository on bitbucket and clone it on the WordPress server. Update the script with your paths:

#!/bin/bash

echo "Finding config details..."
BLOG_DIR=/var/www/html
DEST_DIR=~/dbdumps/wellbeingbaristabackups/
DB_NAME=`echo "<?php require_once(\"${BLOG_DIR}/wp-config.php\"); echo DB_NAME;" | php`
DB_USER=`echo "<?php require_once(\"${BLOG_DIR}/wp-config.php\"); echo DB_USER;" | php`
DB_PASS=`echo "<?php require_once(\"${BLOG_DIR}/wp-config.php\"); echo DB_PASSWORD;" | php`
DB_HOST=`echo "<?php require_once(\"${BLOG_DIR}/wp-config.php\"); echo DB_HOST;" | php`
 
#Compress the WordPress files
echo "Compressing WordPress files..."
FILES_TAR_FILE_NAME=${DEST_DIR}blogFiles-$(date +%Y%m%d).tar
tar -cjf $FILES_TAR_FILE_NAME $BLOG_DIR

#Dump the database contencts
echo "Taking a database dump..."
DB_TAR_FILE_NAME=${DEST_DIR}blogFiles-$(date +%Y%m%d).sql
mysqldump --user=$DB_USER --password=$DB_PASS --databases $DB_NAME --host=$DB_HOST > $DB_TAR_FILE_NAME

#Push to git
echo "Sending files to remote"
cd $DEST_DIR
git add .
git commit -m "Another daily backup"
git push origin master

The final step is to configure the scheduling. The above script assumes that the backups will be taken not more than once daily. If you need more frequent backups, the date timestamp of the files needs to include hours or possibly minutes. Next is the scheduling for the script. To enable this we need to create a Linux cron job. Open your terminal and type in the following command:

sudo crontab -e

This will open the cron editor. You might need to change the script name and/or location, but if you named the script “wordPressBackup.sh” and saved it in location “/home/user/dbdumps/”, then add the following line in the crontab editor.

0 1 * * * /home/user/dbdumps/wordPressBackup.sh

This instruction will perform the backup, every day at 1 am.

6. Conclusion

In this article, we have seen how to make sure your WordPress site is backed up properly.

We have also used tools such as FTP and GIT to store our backups safely.

The post How to Backup a WordPress Site for free! appeared first on AYALR.

]]>
How To Make Custom WordPress Rest API Endpoints https://ayalr.com/how-to-make-custom-wordpress-rest-api-endpoints/ Mon, 31 May 2021 20:03:57 +0000 https://ayalr.com/?p=241 Do you want to request data through an APO from WordPress? Follow this article, to learn how to make easy and quick custom WordPress Rest API endpoints using PHP.

The post How To Make Custom WordPress Rest API Endpoints appeared first on AYALR.

]]>
More and more web services are nowadays consuming information and processing data directly from blogs. A JSON WordPress Rest API endpoint and text scraping are two common methods of linking blogs and web services. In this article, I am going to describe how I have created a JSON endpoint for the Cooked WordPress plugin to query recipes that will be used by a mobile app.

There is no doubt that the Cooked WordPress Plugin is one of the best alternatives for a food blog. It has amazing easy-to-use features that help you manage and add new recipes to your food blog efficiently like our sister blog WellbeingBarista food and lifestyle blog. Additionally, we thought that we could use the same recipes for a Recipes/Food app but felt that exporting and importing the data manually would be a little messy and inefficient.

So why not adding a JSON endpoint for the Cooked plugin?

Retrieving Recipes Stored by the Cooked WordPress Plugin

It seems that as administrators of the blog, we might be a little bit picky and managed to find out a missing feature! Currently, at the time of writing, there is no JSON endpoint API that allows you to dynamically export recipes albeit this is a very important feature if you need to hook up any web services with the blog.

Nevertheless, after investigating how the recipes are stored in the main WordPress database, it was trivial to come up with a spartan functional way to create this JSON endpoint. This simple solution offers a Rest API with two JSON endpoints:

  1. An endpoint to get a list of available recipes – https://your_domain.com/wp-content/plugins/your_plugin_name/api_name.php
  2. Another endpoint to return the detailed recipe object – https://your_domain.com/wp-content/plugins/your_plugin_name/api_name.php?recipeId=261 where 261 is an id retrieved from the response of the first endpoint.

Unfortunately, there was no database field to indicate the last modification date of the recipe, hence an SHA-based hash function was used to generate the version. A version is a very important piece of information for any web service consuming the JSON endpoint API. Otherwise, it would not be efficient to react to distinct recipe changes or updates.

WordPress Rest API – the PHP Source Code

Now let’s look at the PHP code that creates the JSON WordPress Rest API with two endpoints.. It should be noted that in order not to replicate config items, it makes use of the existing WordPress configuration.

<?php require "../../../wp-config.php"; ?> 
<?php 

$servername = DB_HOST; 
$username = DB_USER; 
$password = DB_PASSWORD; 
$dbname = DB_NAME; 

// Create connection 
$conn = new mysqli($servername, $username, $password, $dbname); 
// Check connection 
if ($conn->connect_error) { 
     die("Connection failed: " . $conn->connect_error); 
} 
if (!isset($_GET['recipeId'])) { 
     // No recipe id is set, hence return all the available ones. 
     $sql = "SELECT postId as recipeId, SHA(metaValue) as version from (select post_id as postId, meta_value as metaValue from wordpress.wp_postmeta where meta_key = '_recipe_settings') AS innerTable"; 
     $result = $conn->query($sql); $resultArray = array(); 
if ($result->num_rows > 0) { 
     // output data of each row 
     while ($row = $result->fetch_assoc()) {  
          $resultArray[] = $row; 
     } 
     echo json_encode($resultArray); } else { 
     echo "{}"; 
     } 
} else { 
     //Load the meta for specified recipe, avoiding SQL injection 
     $stmt = $conn->prepare("SELECT meta_value FROM wordpress.wp_postmeta WHERE meta_key = '_recipe_settings' and post_id = ?"); 
     $stmt->bind_param('i', $_GET['recipeId']); 
     $stmt->execute(); $result = $stmt->get_result(); 
     if ($result->num_rows > 0) { 
           $row = $result->fetch_assoc(); 
           echo json_encode(unserialize($row["meta_value"])); 
     } else { 
           echo "{}"; 
     } 
} 
$conn->close(); 
?>
Code language: PHP (php)

The PHP file ‘api_name.php’ was copied into a directory under plugins. However, it can be created anywhere as long as the reference to wp-config.php (line 1) is updated accordingly.

Testing the API

Now, using an API Testing Tool such as Postman or SoapUI call the two endpoints with the required parameters and check the responses.

The result should be like the following sample responses.

Sample Responses

A Sample Response of the WordPress Rest API Endpoint that returns a recipe detail given an Id.
Sample endpoint’s response when requesting for recipe details

A Sample Response of the WordPress Rest API Endpoint that returns all recipe Ids
Sample endpoint’s response when requesting all recipes in database.

Conclusion

After setting up the PHP file, your Cooked WordPress Plugin installation will have a WordPress Rest API. Beware that this is only a proof of concept that happened to extract data saved by the Cooked Plugin but the concept can be used for any data found on WordPress.

The post How To Make Custom WordPress Rest API Endpoints appeared first on AYALR.

]]>
How To Make WordPress Hosting Migration To Bluehost Now https://ayalr.com/wordpress-hosting-migration-to-bluehost/ Sat, 29 May 2021 18:14:48 +0000 https://ayalr.com/?p=222 5 Minute read. This is a proven use case of WordPress hosting migration from my previous host to Bluehost. I have smoothly transferred a lifestyle blog that I manage in an hour with no downtime. Let me quickly guide you through the steps needed to ensure a guaranteed smooth migration for free. Why choose Bluehost …

How To Make WordPress Hosting Migration To Bluehost Now Read More »

The post How To Make WordPress Hosting Migration To Bluehost Now appeared first on AYALR.

]]>
5 Minute read. This is a proven use case of WordPress hosting migration from my previous host to Bluehost. I have smoothly transferred a lifestyle blog that I manage in an hour with no downtime. Let me quickly guide you through the steps needed to ensure a guaranteed smooth migration for free.

Why choose Bluehost for your WordPress hosting migration?

My blog started its life on a very humble IT infrastructure. For about two years I hosted the blog in my own apartment running on salvaged hardware. Being an IT geek this is all too possible, and it can initially save you important funds that can be used elsewhere.  This implied putting in more time and effort to keep up with uptime, stability, security, and of course scalability in face of constantly increasing traffic. 

However, there comes a time when a blog owner needs to upgrade and outsource to a trusted supplier. In my case, the blog grew beyond a certain stage and it made sense financially and infrastructural point of view to upgrading my hosting. Alternatively, you might want to migrate, to host it in a place that ensures quick access to your main traffic source, uptime, scalability, security, and support. If you made your choice, now it’s time to migrate!

There are WordPress hosting companies around every corner. You can also create your own setup on some cloud like Azure, AWS, or Google Cloud. It took me considerable effort to compare and decide on my WordPress host. After investigating different pricing models and applying performance tests using tools like GTMetrix, I chose Bluehost. Apart from my research, Bluehost has been a recommended host by WordPress itself since 2005. There are various plans to choose from, but for the price of 2 cappuccinos a month, I purchased a plan that gives me unlimited storage, websites, databases, and bandwidth. They also throw in a free domain for a year, and a very good tried and tested customer support. 

The WordPress Hosting Migration steps

From this first step till the last one, make sure you don’t change any blog content, as such changes will likely be lost. Viewers will still be viewing content from the original WordPress until the last step is completed.

Backing Up Your WordPress Site

  1. Using FTP, or SSH download a copy of the wp-content directory of your original blog. 
  2. Login to your Bluehost admin and create a new WordPress site. Take note of the chosen directory name. Take note of the temporary website URL. Also, take note of the name of the newly created database. We will be using them in future steps.
  3. Using a MySQL client tool, or phpMyAdmin, take a database dump of the original blog. This creates a file with a .sql extension. Open it in a good text editor and remove the highlighted create database command. Also, replace the existing database name (‘wordpress’ in this example) with the name discovered in step 2.
WordPress Hosting Migration - Replacing the database name
WordPress hosting migration SQL file

Uploading your WordPress Site to BlueHost

  1. Using the Bluehost admin, create an FTP account so that it will allow you to upload the wp-content folder downloaded in step 1. You can also ask Bluehost customer support to enable SSH access to your server and do this step via SSH.
  2. Open the phpMyAdmin from Bluehost admin. Select the database identified in step 2. Select all tables, and drop them. After dropping the original tables, use the import function using the .sql file from step 3. Take note of the prefix for the imported table names. Usually, the prefix is ‘wp_’, but this might differ.
  3. With the database imported, always using phpMyAdmin, open the contents of the wp_options table. Replace the values for keys ‘siteUrl’, and ‘home’ with the temporary URL discovered in step 2.
  4. Go to the website management in Bluehost, and log in to the WordPress admin. Go to Settings > Permalinks, and just press save without making any changes.
  5. Using the FTP file access, open the wp-config.php file. Search for the key ‘$table_prefix’, and set the value discovered in step 5.
  6. At this point, you should be able to open your browser, point it to the URL value used in step 6, and the site should appear.You have now just finished your WordPress Hosting Migration!

Testing your WordPress Site on BlueHost

  1. You can now test the temporary site being hosted by Bluehost. Test navigation, make sure all your images and articles load correctly. Once you’re happy with the testing, you need to revert the change in step 6. This time use your proper site address as value.
  2. It is time to make your domain point to Bluehost. This final set of steps might take a number of days, as it all depends on DNS propagation which is out of everyone’s control.
  3. Using your domain provider settings, change the DNS values to:
ns1.bluehost.com
ns2.bluehost.com
DNS Values for your existing domain
  1. Using the ‘Assign’ functionality on Bluehost, type in your domain name. Bluehost will verify that you own the domain by checking its DNS configuration. Once verified, continue to assign it to the directory discovered in step 2.
  1. From now onwards you need to wait for DNS propagation to be over. Until this is complete, some viewers will still be getting content from your original host. In our case we stopped seeing traffic on the old host after 2 days. 

The above guide allows you to move your WordPress from an old hosting provider to bluehost. With some minor modifications, it can be used to transfer WordPress to any other hosting provider. From my personal experience with my blogs, I strongly recommend bluehost.com. This post contains affiliate links.

The post How To Make WordPress Hosting Migration To Bluehost Now appeared first on AYALR.

]]>