Develop and debug a WordPress plugin from the scratch
Tags: wordpress, programming, php, vscode
Published: 2021-04-28 14:05:01

I had never been a PHP fan, I born as a C# developer and honestly is quite a fun and easy life with all the IDE and tools doing most of the stuff automagically. 

When I started with PHP many years ago, one of the main difficulty I found was not being able to debug properly and that always affected my development decisions. 

Recently I decided to get back on PHP and specifically I was interested in developing a WordPress plugin. 

Here I want to share with you what I've learned and done in order to debug and properly create a simple WordPress plugin from the scratch. 

We will use Laragon and VS Code.

Let's start :) 

# Install Laragon and WordPress on the local machine

The first thing to do is to install a web server and add a WordPress project. I used Laragon as the web server. 

1. Download and install [Laragon](https://laragon.org/)
2. Download [WordPress](http://wordpress.org/) and extract it in the Laragon project folder (e.g. C:\laragon\www) 
3. Start Laragon
4. Laragon in automatic will add to the host file a reference to your project as {project_name}.test (project_name is the folder name)  

In my case I extracted WordPress under a folder named `wp` (e.g. C:\laragon\www\wp)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w8tfc49y1m2jpx7leevn.png)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tv5k0ylrmigh8b62oga6.png)

# Install PHP

Then we can install PHP, before doing so check the PHP version installed with Laragon, you can verify that by going in the Laragon installation folder then `\bin\php`, here you will find a folder named like `php-7.2.19-Win32-VC15-x64` in this case `7.2.19` is the version. 

We can now go to the official [PHP website](http://www.php.net/) and download the same version as Laragon, be careful and download the Thread Safe PHP version. 

Once the download ends, extract the content of the archive in a folder on your disk, I use `C:\libs` for all the libraries I download. 

You need to add the path where you’ll extract PHP to the environment path (user environment path).  

# Configure VSCode to properly debug PHP 

Open VS code, go to settings and check the following values

1. `php.validate.enable` true
2. `php.validate.executablePath` e.g. C:\libs\php\php.exe
3. `php.validate.run` onSave

Then install the following extensions

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hthm68vdf96vvw2ddciq.png)

# Install xDebug

## Debugging CLI PHP Scripts

To install xDebug first we need to gather the PHP information for our local environment, to do that run `php.exe -i > output` this will print out, in the output file, all the info we need to proceed with the installation. 

Go to [xdebug.org/wizard](xdebug.org/wizard) and paste the PHP information stored in the output file, the wizard will inform you on what’re the next steps. 

In my scenario I’ve 

1. Download php_xdebug-3.0.4-7.4-vc15-x86_64.dll
2. Move the downloaded file to C:\php\ext (this might different, check your installation folder)
3. Create `php.ini` in the same folder as where `php.exe` is and add the line `zend_extension = C:\php\ext\php_xdebug-3.0.4-7.4-vc15-x86_64.dll`

Pretty straightforward ;) 

## Enable remote debugging

In the `php.ini` file, you just placed the `zend_extension` configuration, add the following lines

```
xdebug.mode = debug
xdebug.start_with_request = yes
xdebug.client_port = 9000
```

## Debugging Laragon projects

Because we will debug projects deployed via Laragon we need to repeat the above configuration steps for the PHP executable installed under the Laragon folder, it’s store in the `bin` folder under the Laragon installation folder.

# Test all together with a simple script

To test all together I’ll script a simple PHP program to output _Hello World_, what a fantasy eh! The goal is to run and debug the script. 

Create a folder, open it in VS Code and create a simple PHP script. The folder part is important we’ll need to create a launch configuration file `launch.json`.

```
<?php
  echo "Hello World";
  echo "end";
  end();
?>
```

Then we can configure the debug options. Hit the debug icon, click _create a launch.json file_ and select PHP, this will create a launch configuration file with two configurations _Listen for Xdebug_ and _Launch currently open script_. Let’s see what these two configurations mean

1. Listen for Xdebug: this config will start listening on the specified port (usually xDebug uses port 9000). Every time you make a request with a browser to your webserver or launch a CLI script, xDebug will connect and VS code will stop on breakpoints, exceptions, etc…

2. Launch currently open script: this config is an example of CLI debugging, it will load and start the current script in CLI, showing all the stdout/stderr output in the debug console. The debug session will be automatically closed once the script ends. 

In the end, we should see two debug configurations, in this very case we need to use the second _Launch currently open script_.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pqv71353ckz27osuz1fi.png)

Done :) 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k7fqcx68kmj87rbu2se1.png)


# Test all together with WordPress

Now let’s take a look at how we can debug a WordPress plugin, is intuitive that we need to use the _Listen for Xdebug_ debug configuration to do that. 

The simplest plugin we could try to debug is `hello dolly`, a built-in WordPress plugin. 

I’ll start by launching my Laragon servers, this will spawn up WordPress I previously installed as a project.

Then I’ll go to my `WordPress project folder/wp-content/plugins` and open the `hello.php` file in VS Code, this is the `hello-dolly` plugin let’s try to debug it. 

In VS Code go to the debug tab and create a new configuration, then click on _Listen to Xdebug_, for test reason place a breakpoint in the `hello_dolly_get_lyric()` return statement (line 49).

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i9o4djemrz3yknj4w62s.png)

Now open a browser and navigate to your WordPress wp-admin service, as you log in the breakpoint should be hit, that is the confirmation our debug process works. 


Finally, we can take care of `folder-mapping` this particular feature will allow us to store and work on the code not directly placed under our WordPress folder, this is crucial to avoid issues like deleting your own code or overwrite the plugin with outdated files. 

Let’s copy the `hello.php` file in a folder somewhere else, could be your desktop, open VS Code and prepare a debug configuration, this time we need to add a little twist to map our PHP file to the one deployed server-side (on another folder on our PC, consider the procedure is valid also for a remote server if that server allows PHP debug).

```
{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Listen for Xdebug",
      "type": "php",
      "request": "launch",
      "port": 9000,
      "pathMappings": {
        "C:\\laragon\\www\\wp\\wp-content\\plugins": "${workspaceFolder}"
      }
    },
    {
      "name": "Launch currently open script",
      "type": "php",
      "request": "launch",
      "program": "${file}",
      "cwd": "${fileDirname}",
      "port": 9000
    }
  ]
}
```

The lines from 12 to 14 describe how VS code should map the current workspace code to the server deployed code. 

Now if you run again the debug, you got to your WP instance in the wp-admin section, you should be able to debug. Consider some errors that might occur when you hit the debug button, this is because in your folder there’re no WP files and Laragon needs to load them; if that happens just start the debug session again and you should be grand. You'll be also able to deeply debug WP files. 

# Conclusions 

Honestly, I found PHP development and debug pretty easy, I remember nightmares and high difficulty in my past it might be me, improving my skills, or better tools on the market. 

Let me know what you think about this article, is my first one on this community and I really appreciate your feedback to improve. 

See you soon in my next article of WordPress Pluging Developement Series.

Cheers ✌