Blog posts under the Debugging category https://webdevstudios.com/category/debugging/ WordPress Design and Development Agency Tue, 09 Jul 2024 21:08:08 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.2 https://webdevstudios.com/wp-content/uploads/2022/07/cropped-wds-icon.white-on-dark-60x60.png Blog posts under the Debugging category https://webdevstudios.com/category/debugging/ 32 32 58379230 User Acceptance Testing https://webdevstudios.com/2022/12/20/user-acceptance-testing/ https://webdevstudios.com/2022/12/20/user-acceptance-testing/#respond Tue, 20 Dec 2022 17:00:51 +0000 https://webdevstudios.com/?p=25667 User acceptance testing can be boiled down to the execution of a series of test scenarios. A test scenario is a sequence of steps that make an important user journey. A user journey is defined as a natural or expected way an actual user will interact with the software. Outside of the computer running the Read More User Acceptance Testing

The post User Acceptance Testing appeared first on WebDevStudios.

]]>
User acceptance testing can be boiled down to the execution of a series of test scenarios. A test scenario is a sequence of steps that make an important user journey. A user journey is defined as a natural or expected way an actual user will interact with the software.

Outside of the computer running the software, user acceptance testing can be very low tech, only requiring a spreadsheet and a stopwatch. The stopwatch is kind of an exaggeration, but if the user journey takes too long, you lose the user.

So you do want to keep performance in mind incase it becomes a barrier for the user in completing the steps. The spreadsheet is the checklist where each test sequence is laid out. A collection of test scenarios is called a test suite.

Example of User Acceptance Testing (UAT)

An example of a test scenario might be as follows:

  • Navigate to the homepage.
  • Click “contact us” link.
  • Observe contact page loads.
  • Fill out contact form completely.
  • Submit form.
  • Verify no errors are present and thank you message displays.

Each point starts with a verb followed by some element of the website. You’ll notice that these steps are pretty simple and a lot of this can be automated for extra testing coverage.

However, you don’t want to skip the human powered UAT because it will be an avenue for reporting unexpected issues and behaviors in the software.

Who can conduct UAT?

Anyone.

User acceptance testing can be done by anyone on the team. It can also be a great task for anyone working adjacent to the project team looking to get involved.

There are arguments to be made that the tester probably should not be the developer, mainly due to blind spots. You can always have more than one person conducting UAT. The more eyes on a project, the more bugs that can be surfaced.

When should UAT be conducted?

After an update has been pushed to an environment.

UAT is a safety check to make sure the expected high level functionality of the site is still intact. A safety check to ensure the site is still useable to the user.

The Importance of UAT

User acceptance testing is the most important testing because it ensures your website and its purpose for existing is still intact. If you spend hundreds or thousands of hours developing software that is unusable to the end user, its basically worthless.

The downside to UAT is that it doesn’t provide the developer with a lot of details about where the issue is occurring. In our example test scenario above, there can be many reasons why the user could be unable to submit a contact form.

It could be a backend issue keeping the whole page from displaying or a frontend bug that is displaying the form incorrectly. This is why it’s important to make informative bug ticket once you do find a bug.

This is a GIF of a character from the movie Starship Troopers, covered in goo, saying, "Thank you, sir."
UAT testers at the end of their review.

Bug Reporting

Here are some best practices for creating a bug ticket. Ultimately you want a ticket to be useful to the developer and the person who will be testing once the fix is complete.

The first thing the developer is going to do is try and reproduce the issue. Your ticket needs to provide all the necessary information for them to do that. For website testing it makes sense to include the following:

  • Consistent title formats
    • An example could look like, “Homepage – Image carousel not rotating”
  • A description of the issue
    • It can help to include which step you were on when the failure occurred.
  • A link to the page where the issue is occurring
  • A screenshot of the issue
  • Mention the device/OS/browser being used when issues seen.
    • Macbook/MacOS/Safari

Things to avoid:

  • Nesting multiple issues in one ticket
  • Creating multiple tickets for the same issue

Conclusion

By implementing user acceptance testing, you can save yourself from a lot of headaches later. Hopefully now, you understand the importance of it. Contact WebDevStudios when you want a team to test the performance of your website.

The post User Acceptance Testing appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2022/12/20/user-acceptance-testing/feed/ 0 25667
Debugging WordPress Using Xdebug, Local, and VS Code https://webdevstudios.com/2022/10/06/debugging-wordpress/ https://webdevstudios.com/2022/10/06/debugging-wordpress/#comments Thu, 06 Oct 2022 16:00:51 +0000 https://webdevstudios.com/?p=25376 This post covers debugging WordPress using Xdebug, Local, and VS Code. This approach to debugging is far superior to logging variables to the error log or to the screen. Getting things set up correctly can be tricky. That’s where this tutorial helps. Xdebug Xdebug is a powerful tool for debugging PHP applications. It conveniently comes Read More Debugging WordPress Using Xdebug, Local, and VS Code

The post Debugging WordPress Using Xdebug, Local, and VS Code appeared first on WebDevStudios.

]]>
This post covers debugging WordPress using Xdebug, Local, and VS Code. This approach to debugging is far superior to logging variables to the error log or to the screen.

Getting things set up correctly can be tricky. That’s where this tutorial helps.

Xdebug in action

Xdebug

Xdebug is a powerful tool for debugging PHP applications. It conveniently comes bundled with Local.

We’re using VS Code for our code editor in this tutorial, as well as some other tools I’ve listed below. Everything included here is the current release and version numbers are noted just in case it might be helpful since things change.

Prerequisites

  • Local v6.4.2+6012: A local WordPress development environment, formally known as Local by Flywheel
      • PHP v7.4.1/v7.3.5/v8.0: Selectable via the Local UI. Choose v7.4.1 or v 7.3.5 for now because PHP 8 has a different Xdebug setup we’ll cover at the end of the article.
  • VS Code v1.70.2: Code editor
  • PHP Debug by Xdebug for VS code v1.27.0: VS Code extension which allows VS Code to talk to Xdebug
  • Xdebug Helper browser extension: Used for explicitly enabling or disabling debugging sessions

I use Windows because that’s what makes me happy, but this guide applies to other environments as well. I just wanted to note that, since the paths I’ll be referencing are Windows-y.

Create a Site in Local

Once all of the prerequisites have been installed and activated, you’ll need to create a new WP site in Local if you don’t have one already. When PHP Versions 7.3.x or 7.4.x are selected in Local, Xdebug Version 2 is used.

When PHP Version 8 is selected, Xdebug Version 3 is used. We’re going to use PHP Version 7.4.1 to start off with and will cover PHP Version 8 at the end of the article.

I’ve named my site xdebugvscode.test. Here are its settings:

Local site settings

Set Up php.ini.hbs Directives

Now that the site has been created, let’s double-check the Xdebug configuration directives in the site’s php.ini.hbs file. This file is located under your site’s conf/php directory.

For me, the path is D:devlocal-sitesxdebugvscodeconfphpphp.ini.hbs. Scroll to the bottom of the file under the [xdebug] section, and verify that you have the directives below set accordingly. If you need to make any changes, be sure to restart your Local site.

; Enable remote debugging.
xdebug.remote_enable=1

; If enabled, the xdebug.remote_host setting is ignored and
; Xdebug will try to connect to the client that made the HTTP request.
; It checks the $_SERVER['HTTP_X_FORWARDED_FOR'] and $_SERVER['REMOTE_ADDR'] variables to find out remote IP
xdebug.remote_connect_back=Off

; Set the port that Xdebug connects to.
xdebug.remote_port="9000"

; Disable the profiler.
xdebug.profiler_enable=0

; Set the profiler's output directory for when we're profiling.
xdebug.profiler_output_dir = "D:/dev/xdebug-profiler-output"

A Note About the php.ini.hbs File When Switching PHP Versions

If you ever change the PHP version for your Local site, Local will save the settings for the previous install of PHP under the {local-site-dir}/conf/php/php-{version-number}directory.

For example, I started out with PHP Version 7.4.1 installed, then switched to PHP Version 7.3.5. Local made a copy of my PHP Version 7.4.1 settings under D:devlocal-sitesxdebugvscodeconfphp-7.4.1.

If you change PHP versions and made any modifications to Local’s php.ini.hbs file, you’ll need to make the changes again, if this is the first time the PHP version has been activated. After that, if you swap between PHP versions, your setting changes will be preserved.

Ensure Xdebug Is Running

To make sure that Xdebug is running, create a file named pi.php in the root of your site and add the following code to it:

<?php
// Output information about PHP's configuration.
phpinfo();

location of the ph.php file

Now load up https://yoursite.test/pi.php and make sure that Xdebug is running. Find the Xdebug section; it will look something like this:
php_info() output
If you’re not seeing this, then Xdebug is not running. Double-check the php.ini.hbs file to ensure that Xdebug is enabled.

Activate Xdebug Helper Browser Extension

Once you’ve installed and activated the Xdebug Helper extension for your preferred browser, make sure to enable debugging by clicking on the icon and selecting Debug. The little bug icon will turn green letting you know that the browser extension will set the appropriate flag to turn on debugging.

Enable the Xdebug helper extension

Open Local Site in VS Code and Save a Workspace

Once the site has been created, go to File > Open Folder in VS Code, then navigate to the site’s directory. Now, save the workspace by going to File > Save Workspace As… and then give the workspace a name.

Install and Activate PHP Debug Extension for VS Code

The PHP Debug extension for VS Code helps to bring everything together. Locate the extension in VS Code’s Extension Browser, and activate it. Make sure to select the one published by the Xdebug team, since there are a few extensions with the same name.

PHP debug extension for VS Code

 

Create a launch.json File for Your Workspace

Next, we will create a launch.json file for our workspace. Click on VS Code’s debugging icon to open the debugging panel, then click on the create a launch.json file link.

Create launch.json step 1

Now select the name of your workspace which you created earlier.

Create launch.json step 2

VS Code will populate the launch.json file with defaults, but we’re going to replace them.

Create launch.json step 3

Go ahead and delete the entire contents of the default launch.json, replace the contents with the settings below, then save the file.

The launch.jsonwill be stored at {local-site-name}/.vscode/launch.json. So, mine is saved at D:devlocal-sitesxdebugvscode.vscodelaunch.json.

 

{
  // 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,
      "log": false,
      "maxConnections": 1, // @see  https://github.com/xdebug/vscode-php-debug/issues/604
      "xdebugSettings": {
        "resolved_breakpoints": "0", // @see https://github.com/xdebug/vscode-php-debug/issues/629 and https://stackoverflow.com/a/69925257/3059883
        "max_data": 512,
        "show_hidden": 1,
        "max_children": 128
      }
    }
  ]
}

When using Local’s PHP Version 7.3.x or 7.4.x, the version of Xdebug in use will be 2.9.0, which had a bug that caused some weirdness with breakpoints. I’ve added some links to the config file above which go into some more detail if you’re interested.

Check out the PHP Debug extension’s Github page for more information about supported settings.

Add a Breakpoint to Your Code

For the purposes of this debugging WordPress demo, I’m going to add a breakpoint to line 48 of  Twenty Twenty-Two’s functions.php file.

To add a breakpoint, hover over the gutter (just to the left of a line number) and a little orange dot will appear. Click it to add a breakpoint.

Click it again to remove it. You can add multiple breakpoints, and the debugger will stop on each one. To keep things simple here, I’ll just add the one.

Adding a breakpoint

Once your breakpoint has been added, you will see it listed in the lower left-hand corner of  VS Code’s debugger panel. It’s also possible to set breakpoints on Notices, Warnings, Errors, etc., but we’ll uncheck all of those for this example.

Debugger breakpoints

Start Debugging WordPress

We’re finally ready to start debugging WordPress! Open VS Code’s debugger panel and click the green triangle to start listening for Xdebug. Use the F5 shortcut.
Start debugging
Once VS Code is listening for Xdebug, the Debugger Controls window will be displayed. The bottom of the VS Code window will turn orange.

Listening for debugger

Now Xdebug is waiting to start the session. To kick things off, just load a page that will hit the breakpoint.

I’m just going to load the homepage of the test site I created. Once I hit refresh on the homepage of the test site, VS Code will be highlighted in the taskbar and the debugger will stop executing code on the breakpoint that I had previously set.

Once a debugging session has started, additional controls will be active on the Debugger Control Panel, and variables will be listed under the VARIABLES section of the Debugging Panel.

Inside a debugging session

We can now use the Debugger Controls to navigate through the codebase:

Debugger Controls

  • Pause/Run (F6): Resumes code execution. Debugger will stop on the next breakpoint if set.
  • Step Over (F10): Steps over a block of code.
  • Step Into (F11): Steps into a block of code.
  • Step Out (Shift + F11): Steps out of a block of code that was previously stepped into.
  • Restart (Ctrl + Shift + F5): Restarts the debugging session.
  • Stop (Shift+F5): Halts execution of the script.

The GIF at the top of this article demonstrates some basic usage of these controls.

Exploring Variables

We can also explore the values of local and global variables using the VS Code’s VARIABLES section within the Debugging Panel.

Exploring variables

PHP Version 8 + Xdebug Version 3 Set Up

When a Local site is configured to use PHP Version 8.X, the bundled version of Xdebug will be Version 3, and there are many changes from Versions 2 to 3.

These changes are covered thoroughly in this guide. Notably, Xdebug Version 3 defaults to port 9003 instead of 9000. I’m going to switch my Xdebug Version 3 setup to use port 9000 for consistency, so I don’t have to change anything in my launch.json file.

Here are the Xdebug directives in my PHP Version 8 site’s php.ini.hbs file. Note that I’ve commented out the line xdebug.start_with_request.

xdebug.mode=debug
xdebug.client_port="9000"
; xdebug.start_with_request=yes
xdebug.discover_client_host=yes

Now that we’ve switched our site to PHP Version 8 if we check the output of our pi.php file that we created earlier, we can see that Xdebug Version 3 is now loaded, where Version 2.9.0 was being used under our PHP Versions 7.3 and 7.4 sites.

Xdebug version 3

One of the cool features that comes bundled with Xdebug Version 3 is the addition of the xdebug_info() function. This is similar to the php_info() function, but it provides more detailed diagnostics for about the Xdebug setup.

To use it, simply add a file to your site’s web root. For example, xdebug-info.php , then add the following contents:

<?php
xdebug_info();

Load that file up in your browser, and you’ll see something like this:

xdebug_info output - debugger not listening

In the screenshot above, the diagnostics log is indicating a problem connecting to the host on port 9000. The reason for this is that I have not enabled VS Code to listen for debugging.

So, I tap F5 to enable debugging, and now when I reload my xdebug-info.php, the Diagnostics Log is clean, and I’m ready to debug. Thanks to fellow WebDevStudios Backend Engineer, Biplav Subedi, for this tip!

xdebug_info output - debugger is listening

Troubleshooting

One common issue that comes up when you’re debugging WordPress is that the debugger does not stop on the breakpoint that you’ve set. This is typically caused by a port conflict—some other process is already using the port that you’ve configured for debugging.

Make sure that no other application is using the port that was configured in the php.ini.hbs and launch.json file. If an application is already using the port you’ve specified, make sure to change your port to something that’s not in use.

To check for a port conflict, end your debugging session in VS Code then run the following command:

Windows CMD: netstat -an | find "9000"

Linux/Mac: sudo netstat -nap | grep ":9000"

You should not see any output after entering these commands. If you do, that means that a process is already using the port you’ve configured for Xdebug (9000) in our example. So you should either configure a different port in your php.ini.hbs and launch.json files, or locate the process that is tying up the port, and stop it/configure it to use a different port.

Bonus: Quick and Dirty Debugging

Sometimes, instead of using Xdebug, I prefer to simply log variables to WP’s error.log file using PHP’s error_log().

I find this handy for real quick stuff, though it’s really not the best way to debug WordPress when things get serious. For this setup, first, add the following statements to your site’s wp-config.php file:

define( 'WP_DEBUG', true ); // Debugging mode activated.
define( 'WP_DEBUG_LOG', true ); // Logs to wp-content/debug.log
define( 'WP_DEBUG_DISPLAY', false ); // Don't add errors to the output.
define( 'SCRIPT_DEBUG', true ); // Load un-minified scripts.

Now, errors will be logged to your site’s wp-content/debug.log file. I typically keep this file open in a side panel of VS Code.

error logging to debug.log

I usually use this one-liner to output values to the debug.log file:  error_log( '$variable_name ' . var_export( $variable_name, true ) );

To make things easier, I trigger this one-liner using a VS Code User Snippet with the trigger logv. Here’s a copy of the debugging-related snippets I use. These are configured in VS Code under File > Preferences >  Configure User Snippets > PHP.

{
// Place your snippets for php here. Each snippet is defined under a snippet name and has a prefix, body and
// description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. Possible variables are:
// $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. Placeholders with the
// same ids are connected.
// Example:
// "Print to console": {
// "prefix": "log",
// "body": [
// "console.log('$1');",
// "$2"
// ],
// "description": "Log output to console"
// }
"Log var_export()": {
"prefix": "logv",
"body": ["error_log( '$1 ' . var_export( $2, true ) );"],
"description": "Do a var_export( $variable ) to PHP error log."
},
"Log print_r()": {
"prefix": "logp",
"body": ["error_log( print_r( $0, true ) );"],
"description": "Do a print_r( $variable ) to PHP error log."
},
"Exit with var_dump()": {
"prefix": "xvd",
"body": ["exit( var_dump( $0 ) );"],
"description": "Exit with var_dump()"
},
"Exit with print_r()": {
"prefix": "xpr",
"body": ["exit( print_r( $0 ) );"],
"description": "Exit with print_r()"
},
"Detailed Error Log": {
"prefix": "logd",
"body": [
"error_log( print_r( (object)",
"t[",
"tt'line' => __LINE__,",
"tt'file' => __FILE__,",
"tt'dump' => [",
"ttt$0,",
"tt],",
"t], true ) );"
],
"description": "Detailed error logging"
},
"Log gettype()": {
"prefix": "logt",
"body": ["error_log( gettype( $0 ) );"],
"description": "Do a gettype( $variable ) to PHP error log."
},
"Debug Filters": {
"prefix": "logf",
"body": ["add_action( 'all', function() { error_log( var_export( current_filter(), true ) ); } );"],
"description": "Logs current filter."
}
}

Conclusion

That’s about it for this post on debugging WordPress using Xdebug, Local, and VS Code. Using Xdebug, you’ll be able to more efficiently and effectively debug code. If you’ve never used it before, I’m sure you will find that Xdebug is a helpful tool in your development arsenal.

The post Debugging WordPress Using Xdebug, Local, and VS Code appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2022/10/06/debugging-wordpress/feed/ 6 25376
How to Fix These 5 Common WordPress Errors https://webdevstudios.com/2020/02/18/fix-wordpress-errors/ https://webdevstudios.com/2020/02/18/fix-wordpress-errors/#comments Tue, 18 Feb 2020 17:00:41 +0000 https://webdevstudios.com/?p=21826 Do these sound familiar? White screen of death. Locked out of the admin. 404 not found. 500 internal server error. I could go on and on, but these are some of the most common errors and issues you will encounter when dealing with a WordPress website. So, if you are close to pulling your hair Read More How to Fix These 5 Common WordPress Errors

The post How to Fix These 5 Common WordPress Errors appeared first on WebDevStudios.

]]>
Do these sound familiar? White screen of death. Locked out of the admin. 404 not found. 500 internal server error. I could go on and on, but these are some of the most common errors and issues you will encounter when dealing with a WordPress website. So, if you are close to pulling your hair out or hiding somewhere thinking and hoping that maybe tomorrow everything will be fixed, and all is going to be right in the world again, don’t worry. You are not alone. It is not the end. WordPress is a stable platform, but there is nothing out of the ordinary about encountering issues. Keep reading to learn how to fix common WordPress errors (without going bald).

WordPress has a huge 35% share of the internet pie. More often than not, the issue you’re having has been documented somewhere with a fix added in for good measure.

Outlined below are five of the most common WordPress errors and issues and how to fix them in the easiest possible way. There will be minimal hand-holding here; you will need to figure out how to get to where you need to go to make changes.

Most of the fixes described below will require you to have some PHP knowledge, knowledge of the WordPress Admin, and an understanding of how to use your hosting platform’s tools. But mostly, you’ll just need common sense and the ability to follow instructions to a T.

Issue 1: Locked Out of WordPress Admin

Scenario: You forgot your password and you don’t have access to the recovery email address.

Fix: The easiest way to fix this WordPress error is to do it via PHPMyAdmin using a SQL statement.

Log into your hosting’s admin panel, then open phpMyAdmin. Select your WordPress Database from the left column, then select the SQL tab and add the following code. Make sure that you’ve changed `new_pasword` and `your_username.`

UPDATE `wp_users` SET `user_pass` = MD5( 'new_password' ) WHERE `wp_users`.`user_login` = "your_username";

However, if you want to create a new admin user, you can drop this instead (make sure to change the values to the right ones).

INSERT INTO `databasename`.`wp_users` (`ID`, `user_login`, `user_pass`, `user_nicename`, `user_email`, `user_url`, `user_registered`, `user_activation_key`, `user_status`, `display_name`) VALUES ('4', 'username', MD5('password'), 'Your Name', 'email@email.com', 'http://www.website.com/can-be-blank', '2011-06-07 00:00:00', '', '0', 'Your Name');

INSERT INTO `databasename`.`wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) VALUES (NULL, '4', 'wp_capabilities', 'a:1:{s:13:"administrator";s:1:"1";}');

INSERT INTO `databasename`.`wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) VALUES (NULL, '4', 'wp_user_level', '10');

 

Issue 2: Maintenance Mode Error

Scenario: You updated your theme and/or plugin and somehow it did not go through the whole process and now you’re stuck in Maintenance Mode.

Fix: There are a lot of fixes to this, but if you need your website up and running in the shortest time possible, you will need to access your website files and you can do that via FTP, your host’s File Manager, or by using an SSH connection. You will need to delete just one file that sits right at the root of your website files -> .maintenance

FTP

 

 

File Manager

SSH Connection

Connect via SSH to your server. Navigate to your website’s root folder and type the following code:

rm .maintenance

Issue 3: HTTP Image Upload Error

Scenario: You could not upload and have the same issue with any image you try to upload no matter the file size. You went through the basic troubleshooting: disabled plugins, default theme, but nothing works. All you can see is a generic HTTP error. There is no explanation, just that you can’t upload anything. It is not a glitch nor a plugin conflict. What else can you do?

Fix: There are three fixes to this WordPress error that you can try:

Increase Memory Limit

Edit your wp-config.php file, found at the root of your WordPress site. Add the following right above where it says: /* That’s all, stop editing! Happy blogging. */

define( 'WP_MEMORY_LIMIT', '256M' );

 

Shared Hosting? Use the .htaccess Hack

Imagick(ImageMagick) is one of the two modules WordPress uses to handle images. And shared hosting usually limits Imagick’s ability to use multiple threads. To fix this error, edit your .htaccess file and add the code below right at the top of your .htaccess.

MAGICK_THREAD_LIMIT 1

 

Ditch Imagick and Use GD Library Instead

Command Tell WordPress to use the GD Library to handle images by adding the code below to your theme’s functions.php file.

wp-content -> themes -> your-theme -> functions.php

function wds_default_image_library( $editors ) {
$gd_editor = 'WP_Image_Editor_GD';
$editors = array_diff( $editors, array( $gd_editor ) );
array_unshift( $editors, $gd_editor );
return $editors;
}
add_filter( 'wp_image_editors', 'wds_default_image_library' );

Issue 4: 404 Not Found Error

Scenario: Out of nowhere, a page on your website is no longer accessible and serving you NOTHING. Nada. Zilch. You might have enabled or disabled a plugin, maybe changed a theme. You’ve already cleared your cache and you know you have the right URL.

Fix: The first thing you can try is to reset your WordPress permalinks. You can just click the Save Changes button and that will reset your permalinks without you changing anything. But, I usually do the extra step of setting it to Plain first and then save. Go check on the post or page to see if it works. If it does, put it back to Post name or whatever your chosen permalinks setting is.

WordPress Dashboard -> Settings -> Permalinks

One extra step to try, if just resetting won’t work, is to rename your current .htaccess to something else. The .htaccess file sits right at the root of your WordPress files. You can then create another .htaccess file and copy the default one below for versions 3.5 and up. If you are running a WordPress Multisite or version 3.4 and below, check this WordPress Support article for the .htaccess to use.

# BEGIN WordPress

RewriteEngine On
RewriteBase /
RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

# END WordPress

After doing that, go through the process of resetting your permalinks again to see if it works. If it does not, change to a default theme. If it works, then the issue is with your theme.

Issue 5: 500 Internal Server Error

Scenario: This is another generic error that does not exactly tell you what’s wrong with your website. All you know is that your website is currently NOT WORKING.

Fix: If you can access your WordPress admin start at step 1. If not, start at step 3.

  1. Disable plugins. Did it work?
    • No – Continue troubleshooting below.
    • Yes – Try to enable your plugins one by one to find the culprit. (Another tip is to create a folder inside /plugins called /disabled [the name doesn’t matter], then move any plugin that you suspect might be hanging the site into that folder to immediately disable it.)
  2. Change to the default theme. Working?
    • No – Down the rabbit hole…
    • Yup – Check your theme for errors and see if you can fix it. If you can’t, find another theme that works for you or create your own. WebDevStudios’ wd_s is a pretty great starter theme to use.
  3. Check if your .htaccess file is corrupt. Rename your old .htaccess and create a new one. Go through the same fix outlined above for Issue 4: 404 Not Found. How about now?
    • Still nothing – Put your thinking cap on and move to the next step.
    • YES!!! – Pour yourself a glass or two and make sure to create a backup of your website.
  4.  Create a backup. Download a new copy of WordPress here. Connect to your site via FTP, delete wp-admin and wp-includes folders. IMPORTANT: LEAVE wp-content ALONE. Once done, upload the wp-admin and wp-includes folder to your server.
    • Nothing is working – It’s time to call customer support and check with them if they can help you fix it.
    • Everything is back to the way it should be.

 

There are lot of other fixes for these errors that you can find online, but the ones outlined in this blog post are my usual go-tos before I do anything else. They work almost all of the time. Just make sure that before you do any kind of change to your website files, your first step should always be: back up everything.

Need help creating a WordPress website that works, error-free?  Contact WebDevStudios today.

The post How to Fix These 5 Common WordPress Errors appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2020/02/18/fix-wordpress-errors/feed/ 2 21826
Diagnosing a Slow WordPress Site https://webdevstudios.com/2020/01/28/diagnosing-a-slow-wordpress-site/ https://webdevstudios.com/2020/01/28/diagnosing-a-slow-wordpress-site/#respond Tue, 28 Jan 2020 17:00:08 +0000 https://webdevstudios.com/?p=21653 Sluggish Website So, your WordPress website is running slow? Back in 2014, the average user would wait up to five seconds for a website to load before abandoning your website. Just a few short years later, that number is now under three seconds. Failure to provide a fast experience for your customers will make a Read More Diagnosing a Slow WordPress Site

The post Diagnosing a Slow WordPress Site appeared first on WebDevStudios.

]]>
Sluggish Website

So, your WordPress website is running slow? Back in 2014, the average user would wait up to five seconds for a website to load before abandoning your website. Just a few short years later, that number is now under three seconds. Failure to provide a fast experience for your customers will make a dramatic impact on your site’s listing on Google searches, as well as turn off your visitors. So what do you do? Start by learning the importance of diagnosing a slow WordPress site.

Website Speed Test

First off, to know how slow your website truly is loading, it’s best to get a baseline from multiple locations across the globe. A fantastic tool to test with is Pingdom Website Speed Test. Using a third-party service helps rule out personal hardware or local internet issues you might have, which will help you diagnose your slow WordPress site by pinpointing problems.

A screenshot from Pingdom that shows the header, "Pingdom Website Speed Test" and the instructions, "Enter a URL to test the page load time, analyze it, and find bottlenecks." Beneath the instructions, there is a white URL field and another white field to enter what geographical area the user would like to test from. The field is defaulted to North America, USA, Washington DC. Next to that is a green button that says, "Start test."

Depending on your target audience’s locality, it is best to run the Pingdom speed test from multiple testing locations relative to your target audience. Once it’s been determined that your site’s load speeds aren’t just localized to you, there are a few easy steps you can make before switching hosts—a solution you may want to consider and a topic I’ll touch on in a future article.

Caching Plugin

Infographic how no cacheing works. Each users requests generates a new response makeing response slower.

Infographic how cacheing works. Each user gets the same response from server not a new respond each time.

In WordPress, all pages are built dynamically, meaning that every time someone visits your website, WordPress has to go out, fetch, and process all the site’s content for each user. This can result in a slow WordPress site.

Often, though, content on your website doesn’t change between users and thus can be cached, meaning that once your website renders a page or post for one user, it can use the same copy for each additional user, cutting down on processing and thus load times. A great paid plugin that can assist with this is WP Rocket; alternatively there is a free caching plugin WP Super Cache if you don’t mind a little setup work.

Compress Images

A significant part that factors into your site’s load time is simply the size of the website itself. Users with slower mobile or rural connections will wait longer if your website uses large graphical assets. When selecting images to use in your site pages and posts, be mindful of the size of images you use. Maybe that profile picture doesn’t have to be 8000 pixels wide.

Although WordPress has built-in compression features for graphics, you might want to consider a plugin like Smush Image Optimization, Compression, and Lazy Load that will help reduce the size of your site images, which means it can help to speed up a slow WordPress site.

The two images below are the same image, however, the top uncompressed version is 1.00MB the bottom one is 0.250MB—a full 75% smaller with little in perceptible quality loss.

This is an photo image of a turtle swimming that has not been compressed.
Picture of Turtle Swimming Uncompressed

 

This is the exact same image as the previous image of a turtle swimming and it has been compressed to be 75% smaller, but there is no perceptible difference between this image and the previous one that wasn't compressed.
Picture of Turtle Swimming Compressed 75% smaller.

Diagnosing Themes and Plugins

Although detecting an under-performing theme or plugin is more complicated than the previous steps, poorly-written plugins or themes can make a huge impact on your site performance by clogging up your server resources with unnecessary function calls. In the end, that means one slow WordPress site.

One way you can go about troubleshooting this is by deactivating all site plugins and switching to a simple WordPress theme like Twenty Twenty. Once your website is mostly vanilla, start slowly activating plugins and testing your site’s performance to see if any particular one makes a significant negative impact on your site’s load time.

Finally, if you have ruled out all options and your website is still loading slow, it might be worth switching to a new website hosting provider. We offer top-notch support, blazing fast hosting, and migration services through our Maintainn brand with affordable pricing. Take a look at Maintainn’s hosting plans to find a solution that works for your WordPress site.

Additional Resources

Another simple website speed testing tool is GTmetrix.


Are you struggling with WordPress performance? Our free guide teaches you everything you need to know to speed up your site. Download and read our “Guide to WordPress Performance” for expert tips.

The post Diagnosing a Slow WordPress Site appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2020/01/28/diagnosing-a-slow-wordpress-site/feed/ 0 21653
Debugging WordPress with Local by Flywheel, (neo)vim, and xdebug https://webdevstudios.com/2019/04/16/debugging-wordpress-with-local-by-flywheel-neovim-and-xdebug/ https://webdevstudios.com/2019/04/16/debugging-wordpress-with-local-by-flywheel-neovim-and-xdebug/#respond Tue, 16 Apr 2019 16:00:53 +0000 https://webdevstudios.com/?p=20143 Introduction Local by Flywheel is a popular tool for getting quick and reliable WordPress installations running on your computer. One of its lesser-known features is the inclusion of xdebug support. xdebug is a PHP extension that allows for real-time debugging of PHP code. Today, we’re going to go over how to get both of these Read More Debugging WordPress with Local by Flywheel, (neo)vim, and xdebug

The post Debugging WordPress with Local by Flywheel, (neo)vim, and xdebug appeared first on WebDevStudios.

]]>
Introduction

Local by Flywheel is a popular tool for getting quick and reliable WordPress installations running on your computer. One of its lesser-known features is the inclusion of xdebug support. xdebug is a PHP extension that allows for real-time debugging of PHP code. Today, we’re going to go over how to get both of these working together within vim to provide a powerful interface that allows for some successful debugging of WordPress.

Prerequisites

Firstly, this tutorial is intended for users of vim or neovim. If you aren’t familiar with how to use vi-like editors, but want to learn, I would recommend running vimtutor in your command line and learning how to move and work in vim before continuing with this post.

Next, you’ll need Local by Flywheel. You can download it here. If you haven’t set up a site before with Local, it is pretty straightforward. You can find a guide for getting started on Flywheel’s blog.

Setup

vim

For vim or neovim, henceforth referred to simply as “vim” (with distinctions for neovim if necessary), you will need the Vdebug plugin. Installation instructions are included on the plugin’s page. I use vim-plug to manage plugins; so my .vimrc looks like this:

""" Vim-Plug
call plug#begin()
Plug 'vim-vdebug/vdebug'
call plug#end()

After adding Vdebug, we’ll need to add some configuration. Before we continue, let’s get Local configured for xdebug.

Local and xdebug

Local ships with the xdebug extension available but not enabled. Each site that you want to debug will need its configuration altered to work with debugging. First, find your Local site site’s directory. In Local, you can view this on the Overview tab, under “Site Path.”

Open your site’s directory, and find the file conf/php/<your site's PHP version>/php.ini. Open this file with any text editor and find the section titled [Xdebug]. This contains the relevant configuration we’re looking for. After modifying this section, your section should look similar to:

xdebug.remote_enable=1
xdebug.remote_connect_back=On
xdebug.remote_port="9000"
xdebug.profiler_enable=1
xdebug.remote_autostart=true
xdebug.remote_handler=dbgp
xdebug.remote_mode=req
xdebug.remote_host=<your local IP>

Note that the remote_host argument should be your computer’s local IP. This will allow the Local machine to talk to your editor.

Save your modifications, and restart your site in Local.

Configuring vim

Open your vim configuration file. Typically, for vim, this will be ~/.vimrc, in NeoVim, your configuration is usually in ~/.config/nvim/init.vim. Add a new section to your vimrc that looks like this:

let g:vdebug_options= {
    "port" : 9000,
    "server" : '',
    "timeout" : 20,
    "on_close" : 'detach',
    "break_on_open" : 0,
    "ide_key" : '',
    "path_maps" : {
        '/app/public/': '<path to your project public folder>'
    },
    "debug_window_level" : 0,
    "debug_file_level" : 0,
    "debug_file" : "",
    "watch_window_style" : 'compact',
    "marker_default"     : '⬦',
    "marker_closed_tree" : '▸',
    "marker_open_tree" : '▾'
}

Note that you need to fill in the path_map item with your local project’s public folder. If your project is located in /Users/you/Local/myproject/, your public folder would be in /Users/you/Local/myproject/app/public/. Also note that the left-hand side points to /app/public/. This is where Local’s server stores your public files. The right-hand side points to the location of the files as you see them in your filesystem.

Now, save your vim configuration and restart vim (you can probably source the configuration, but Vdebug can be a little weird sometimes). Open a file in your project. Let’s try wp-config.php to start. Find a line with code before wp-settings.php is included and press <F10> on your keyboard.

The line should change color. In my editor, it shows a green line where I set the breakpoint:

Now, press <F5> and you should see a message in the status line saying that “Vdebug will wait for a connection in the background.” Visit any page in your site, and you should see Vdebug connect and pause on the line you set as a breakpoint:

Troubleshooting

Here are some tips if you’re having trouble with Vdebug:

  • If the debugger is attaching and then stopping, verify the path_maps configuration.
  • If the debugger is not attaching, verify your Xdebug configuration in your php.ini.

Working with the Debugger

Author note: the following code takes place in the twentynineteen theme. The premise of this exercise is ridiculous, and meant to be an example of how to use the debugging functionality.

Vdebug includes a number of default key mappings, as well as some commands to help evaluate your code. Open your theme’s functions.php and add the following:

add_filter( 'the_content', function( $content ) {
    if ( is_admin() ) {
        return $content;
    }

    return str_rot13( $content );
} );

Now, travel to a single post on your site’s frontend, and view a post:

Whoops, seems something has gone wrong! Let’s suppose this code is buried somewhere deep in our included files; it could be a pain to find the source of this issue. With xdebug, we can trace the code back to our bad filter—the one that we “totally don’t know about…”

First, open up template-parts/content/content-single.php, and find the line calling the_content:

23         the_content(
24             sprintf(
25                 wp_kses(
26                     /* translators: %s: Name of current post. Only visible to screen readers */
27                     __( 'Continue reading<span class="screen-reader-text"> "%s"</span>', 'twentynineteen' ),
28                     array(
29                         'span' => array(
30                             'class' => array(),
31                         ),
32                     )
33                 ),
34                 get_the_title()
35             )
36         );

Since we know our issue is in the content being output, move your cursor on the line with the call to the_content and press <F10> on your keyboard. The line should highlight to indicate that you have set a breakpoint.

Before continuing, it’s a good time to review some of Vdebug‘s key mappings from the Quick Guide section of the README:

<F5>: start/run (to next breakpoint/end of script)
<F2>: step over
<F3>: step into
<F4>: step out
<F6>: stop debugging (kills script)
<F7>: detach script from debugger
<F9>: run to cursor
<F10>: toggle line breakpoint
<F11>: show context variables (e.g. after "eval")
<F12>: evaluate variable under cursor
:Breakpoint <type> <args>: set a breakpoint of any type (see :help VdebugBreakpoints)
:VdebugEval <code>: evaluate some code and display the result
<Leader>e: evaluate the expression under visual highlight and display the result

We will primarily be focused on <F5>, <F3>, <F4>, <F9>, and <F10>. Remember, if you get lost, you can always press <F6> to quit the debugger and then start again.

Next, to start the debugger, press <F5>. You should see the following message in your status line: “Vdebug will wait for a connection in the background.” Reload the page in your browser and you should be presented with the debugging window.

The debugger should halt on our breakpoint. From here, we’ll want to “step into” the function calls to decipher what’s going on using <F3>. When we first step in, you’ll notice we’re not inside the_content, but __. What’s going on? PHP executes methods from the innermost function call to the outermost. Since our breakpoint is actually on a set of nested function calls, we’ll need to press <F4> to step out” of each function until we get to the_content:

Once we’re in the content, we can see a call to apply_filters. Knowing how WordPress works with Actions and Filters, it’s a safe bet that our content is being modified in a filter. Move your cursor to the line calling apply_filters, and press <F9> to allow the program to run until we get to that line.

Next, press <F3> to step into apply_filters. I’ll tell you, this function is a little confusing. We just want to worry about the line that actually calls the filter methods:

    $filtered = $wp_filter[ $tag ]->apply_filters( $value, $args );

Put your cursor on that line and press <F9> again, and then “step in” with <F3>. As you enter the apply_filters method, bear in mind that the crux of WordPress hooks are callbacks. With that in mind, it’s safe to say the following lines are where the magic happens:

282                 // Avoid the array_slice if possible.
283                 if ( $the_['accepted_args'] == 0 ) {
284                     $value = call_user_func_array( $the_['function'], array() );
285                 } elseif ( $the_['accepted_args'] >= $num_args ) {
286                     $value = call_user_func_array( $the_['function'], $args );
287                 } else {
288                     $value = call_user_func_array( $the_['function'], array_slice( $args, 0, (int)$the_['accepted_args'] ) );
289                 }

Lines 284, 286, and 288 all use call_user_func_array in some form or fashion. Place your cursor on each line and press <F10> to add a breakpoint, and then hit <F5> to continue execution. The debugger will begin breaking on one of those three lines.

The Watch Window

Vdebug displays a window where you can watch the variables that are available in various scopes. By default, the “Locals” scope is shown.

This is a window just like any other vim window. Move your cursor to the Locals window, and scroll down until you find the $the_ array (hint: you can search with normal vim commands); expand it by using the <Enter> key. Next, you should look at the value of $the_["function"]. Notice that this will either be an array or a string. Expand the array or view the string with each run of <F5>, looking for anything that may stick out as odd.

Did you find it? There’s a Closure. Since we can’t see what it does here, we’ll need to “step in” again with <F3>. The debugger now drops us into the offending method—the filter we added earlier calling str_rot13.

Wrapping Up

With this ridiculous example, I hope you are able to use xdebug in your own projects to effectively debug. Understanding the WordPress codebase is crucial to being an effective developer, and getting down and dirty with a debugger is a great way to learn how truly complex a system can be.

Tips

  • Vdebug can be fickle – you may need to hit <F6> a couple of times to close the debugger completely.
  • Use :help Vdebug and read the documentation to learn about things like <leader>e.
  • Use project-specific .vimrc files to set up your Vdebug paths:

In the following examples, use .vimrc for vim and init.vim for neovim:

" In your ~/.vimrc or ~/.config/nvim/init.vim
set exrc " see :help exrc

" At the BOTTOM of your RC file:
set secure

This will allow you to set up a configuration for each project. vim with search for either .vimrc, _vimrc, or .exrc in your current directory and load it if found. For neovim, the file names are .nvimrc, _nvimrc, and .exrc. I tend to work from the wp-content folder to make use of tags for my plugins and themes. Depending on where you start your editing, place your RC file in the appropriate location and add your vdebug_options configuration in there. Here’s mine in ~/src/WDS/local/lab/app/public/wp-content/.nvimrc:

" Local 'Lab' {{{
let g:vdebug_options= {
    "port" : 9000,
    "server" : '',
    "timeout" : 20,
    "on_close" : 'detach',
    "break_on_open" : 0,
    "ide_key" : '',
    "path_maps" : {
        '/app/public/': '/Users/phatsk/src/WDS/local/lab/app/public/'
    },
    "debug_window_level" : 0,
    "debug_file_level" : 0,
    "debug_file" : "",
    "watch_window_style" : 'compact',
    "marker_default"     : '⬦',
    "marker_closed_tree" : '▸',
    "marker_open_tree" : '▾'
}
" }}}

Now, I don’t have to worry about resetting things in my init.vim whenever I switch projects!

Actual Conclusion

You made it! In this post you (hopefully) learned:

  • How to enable xdebug in your Local installations
  • Install the Vdebug plugin for neo/vim
  • Effectively use Vdebug to track down bugs in code.

Happy bug squashing!

The post Debugging WordPress with Local by Flywheel, (neo)vim, and xdebug appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2019/04/16/debugging-wordpress-with-local-by-flywheel-neovim-and-xdebug/feed/ 0 20143
Database Management https://webdevstudios.com/2018/06/14/database-management/ https://webdevstudios.com/2018/06/14/database-management/#respond Thu, 14 Jun 2018 16:00:31 +0000 https://webdevstudios.com/?p=18684 What Is Database Management? Very simply put, database management is knowing how to access, configure, debug, and manage your database. For some website owners, this isn’t really a concern. Even developers rarely need to poke around with the database, and for many of us, it’s just a piece of software that someone configured once and, as Read More Database Management

The post Database Management appeared first on WebDevStudios.

]]>
What Is Database Management?

Very simply put, database management is knowing how to access, configure, debug, and manage your database. For some website owners, this isn’t really a concern. Even developers rarely need to poke around with the database, and for many of us, it’s just a piece of software that someone configured once and, as many of us like to say, “We’ll never need to touch it again.” This is a typical understanding of database management, especially in the context of WordPress, with the real ins-and-outs of the entire foundation of your website going largely ignored or, at the very least, just not really being thought about.

Now is a good time to stop and explain exactly what a database is. Ready? Wait for it… it’s a base… for your data.

Image result for bad joke dog

Okay, terrible jokes aside, a database is where all of the persistent data for your website live. Depending on how and where your website is located, the database may be on its own server, or it may be sharing the server with your web server. It could be a Relational Database Management System (RDBMS), such as MySQL, Oracle, or MS SQL, to name a few, or it could be a NoSQL database such as CouchDB or Cassandra. This particular article will deal with RDBMS and MySQL/MariaDB in particular since it’s the most widely used RDBMS for WordPress.

Speaking of SQL, what is it? SQL stands for Structured Query Language, and it’s how both humans and programs communicate with the database. Within SQL are all the commands you need to get, modify, create, and delete information. The other good thing about SQL is that it’s a standard adopted by most RDBMSes on the market.

For instance, I can write a simple query that will work in MySQL, PostgreSQL, MS SQL, and Oracle, with little or no tweaks. A “gotcha” here is that all of these RDBMSes implement their own extensions on top of the SQL standards they support, and while most are SQL or ACID compliant, the level of compliance varies between products and even between versions of the same product. RDBMS-specific features include things like Flashback queries in Oracle or tsvector queries in PostgreSQL. Generally, when looking up SQL documentation, it’s best to try and find solutions specific to your RDBMS.

But Why Do I Need to Know This Stuff?

So, why is it important to learn about your database? For starters, we’re in a world where things go wrong all the time. “It’s easy—just one button and you’re done,” or, “It’s a DNS switch, nothing major,” or, “Just push the patch live and see what happens. I’m sure it won’t do any harm.”

I estimate around $10,421 in nickels for every time I’ve heard those phrases and something went wrong.* When things go south, understanding even how to simply access the database can be crucial to getting your site back in working order. Other reasons you may want to really know how things work in your database include:

  • You decide to move to a new hosting provider and you need backups
  • There’s a change that would be tedious through your CMS but trivial in the database
  • Troubleshooting odd behavior or data
  • Monitoring your database when identifying sluggish behavior in your website
  • Making new friends**
  • When you’re developing a new feature and want to understand the relationship of data in your application

There are plenty of other reasons you may want to look around in the database, and once you are familiar with what it does and how it works, you can feel (mostly) confident that you can peruse the raw data without breaking anything. For some tasks myself, I find it much easier to write a quick SQL query that gets the data I need instead of digging through WordPress trying to find it. This is especially true if you work on several projects throughout your day or week and need to do a lot of context switching.

Getting the Right Tools

There are plenty of tools out there to access your database, and I’ll outline a few here:

  • Sequel Pro is pretty much the de facto SQL client for MacOS. It’s free, open-source, and very reliable
  • Navicat is a paid product for accessing various RDBMS servers and has products for Windows, MacOS, and Linux
  • HeidiSQL is a free, open-source SQL client for Windows
  • phpMyAdmin is another open-source SQL administration client with a twist – it runs on your web server instead of being a standalone application
  • The command-line, which most, if not all, SQL servers provide a set of command-line tools to interface with your database. It takes more knowledge of SQL to get up and running, and to be able to do anything, but some people prefer the simplicity of the terminal over sometimes-frilly GUI clients, like the ones above.

Once you have a SQL client installed, you can set up a connection to your SQL server. Depending on where your site is hosted, you may need to contact your site administrator to request this information. If you have a development server (and you should), then pointing your client to the dev server will give you the freedom to poke around without worrying about destroying your site in the process. Which leads us to the next topic…

Backups, Backups, Backups

Any time you are dealing with a database, whether you want to alter a single row or try out some new tricks, take a backup. All of the above programs offer options to export your data to a SQL file. Backups will save you in a crisis, and give you peace of mind while digging into your database. As a rule of thumb for myself, I won’t do any operation on live production data unless I have a backup. Sometimes it’s easy to write a query with two parameters swapped, or missing a clause to limit the query’s scope, and a backup is about the only “undo” button you have in those situations.

Further, your hosting provider should provide a means of taking regular backups. If this isn’t enabled by default, be sure to set it up; if it’s not available, ask your provider for tips on how to connect to your database so that you can take your own backups. If your site is important enough to you, however, and your provider doesn’t provide automatic backups, it may be worth looking to host your site elsewhere.

For WordPress, you can read more about backups on the codex entry for Database Backups.

Cache Me Outside

I’m only briefly going to touch on caching, since it’s a bit technical to set up and beyond the scope of this post, that said: caching is great, especially if you have a site with a large volume of content or even just lots of users.

In the WordPress world, plugins like W3 Total Cache or Rocket Cache can provide caching solutions to improve your site’s performance and take some of the strain off of your database. Another important note about the WordPress database and caching is knowing what functions are cached by WordPress and which cause database hits. Some methods in WordPress force a fresh lookup of data, which can slow down your application. These methods usually have counterparts that are cached and should usually be used instead. An example of one such function is wp_get_object_terms, which suggests using get_the_terms() instead unless you absolutely need fresh data (caching in this sense refers to data cached in the current session, so a fresh page load would still pull uncached data on the first call of wp_get_object_terms). Always be sure to carefully read the documentation to ensure the method you’re using is proper and performant for the task.

WordPress and the Database

Most of what I’ve covered so far is pretty WordPress-agnostic, so now I’m going to touch on the two together. WordPress was written for MySQL, and although there is some support for alternatives, odds are you’re either running MySQL or MariaDB (a fork of MySQL) if you’re running WordPress. MySQL is well-documented, and whilst MariaDB is a fork, it has its own documentation which covers the same ins-and-outs as MySQL, while providing information specific to MariaDB.

You may have configured your database when you first installed WordPress, and you can find out about your database credentials by looking at your project’s “wp-config.php”, where you can find the DB_NAME, DB_USER, DB_HOST, and DB_PASSWORD constants. More reading on this can be found on the WordPress Codex.

Structure

The database is at the core of WordPress. It’s where your posts, tags, users, theme settings, everything is kept. When you start looking at how the database is structured, you can see why WordPress is built on a Relational Database Management System: Posts have IDs, which connect to the wp_postmeta table (on the post_id column), and taxonomy terms are related via the object_id column on the “wp_term_relationships” table. Meanwhile, the comments table is linked back to posts, and even attachments (which are posts as far as the database is concerned) reference their parent post through relational data.

Side note: if you’ve been doing Database Things™ for a while now, you’re probably wondering why WordPress doesn’t really make use of things like foreign key constraints or other key-based relational data. The reason mostly seems to be from the fact that WordPress defaulted to the MyISAM engine for its tables. While offering better performance for things like largely static record reads (what you expect on a blog), it lacked certain features such as Foreign Key Constraints.

For multisite, you’ll notice that most of the tables in standard WordPress are “duplicated” in a sense for the subsites, with prefixes containing the site’s ID. So if your blog “food.coolblogs.com” is site ID 3, its tables will be prefixed with wp_3_. Note that some tables, like wp_users, are shared across all sites, with WordPress using meta keys to differentiate user roles across sites.

Tips for WordPress Database Management

  • Backups – I may have touched on this previously, but it never hurts to reiterate: always take a backup before touching the database
  • Transactions – Typical WordPress installations using MyISAM engines do not support transactions, so be careful when executing SQL queries in WordPress and test your queries on your local machine or a dev instance before running them in production
  • Filters – Practically every part of the queries that get built by WordPress internally for WP_Query can be filtered and adjusted as needed:
    • posts_fields – Filters the SELECT clause of the query
    • posts_search – Filters the search SQL that is used in the WHERE clause of WP_Query
    • posts_search_orderby – Filters the ORDER BY used when ordering search results
    • posts_where – Filters the WHERE clause of the query
    • posts_join – Filters the JOIN clause of the query
  • Serialized data – WordPress makes heavy usage of serialized data to store objects in the database. If you are ever doing large data operations directly on the database, such as replacing one domain with another in a column, it’s important to ensure the integrity of the serialized data afterward. There are several plugins and code snippets on the web that can help you fix things up again. WP Engine also has a blog post explaining serialization and potential gotchas. (Disclaimer: While we work with WP Engine on several projects, I found that blog post organically via Google.)
  • Monitor your performance – Plugins like Query Monitor can give you an under-the-hood look at what WordPress is doing when it works with the database, and can provide feedback that can be used to tweak for performance, reveal bottlenecks, or uncover bugs in custom query implementations. Similarly, you can use command-line tools like mytop to get an overview of the load on your database server.

For further reading on WordPress and the Database, check out the codex page for the Database Description.

Final Thoughts

There’s a lot to learn about WordPress and the database, and if you’re willing, you can get an in-depth understanding of how the pieces fit and better manage your data. There’s a certain feeling of empowerment in understanding the database, and being able to know that you don’t need to panic when something goes wrong makes dealing with fires a lot less stressful.

If like most of us you’re busy and don’t have time to dig into all of this, then the fine folks here at WebDevStudios can help you manage and optimize your database.


* These numbers are best-guess, and I’ve probably actually heard those phrases far more than 2000 times.
** A SQL query walks into a bar, finds two tables and asks, “May I JOIN you?”

The post Database Management appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2018/06/14/database-management/feed/ 0 18684
Rubber Ducking https://webdevstudios.com/2017/08/01/rubber-ducking/ https://webdevstudios.com/2017/08/01/rubber-ducking/#comments Tue, 01 Aug 2017 16:00:25 +0000 https://webdevstudios.com/?p=17377 One of my favorite things to do as a developer is rubber ducking with other devs. If you aren’t familiar with rubber ducking, the term comes from the book The Pragmatic Programmer in which a dev would explain, line by line, their code to a rubber duck. Writing code is hard, and interesting, and tricky, Read More Rubber Ducking

The post Rubber Ducking appeared first on WebDevStudios.

]]>
One of my favorite things to do as a developer is rubber ducking with other devs.

If you aren’t familiar with rubber ducking, the term comes from the book The Pragmatic Programmer in which a dev would explain, line by line, their code to a rubber duck.

Writing code is hard, and interesting, and tricky, and challenging. And frustrating. And disappointing. And humbling. This is especially so when faced with a bug we can’t identify, or a side effect that makes no sense.

I often take to our company Slack when I’m in a sticky situation, asking for someone that isn’t busy to rubber duck. It seldom matters who is available. The role of ‘duck’ isn’t to solve the problem. It’s to listen, occasionally ask questions, and relate to the feeling of being ‘stuck.’ They don’t need to know the project, my IDE, or even understand the code.

I’ve announced, “I need a rubber duck to help me with some weird js modal issues,” and ended up discovering my issue was with post content. I’ve had a rubber duck session that took ten minutes. Then I realized I was testing on staging while making code changes on my local.

I rubber ducked my first WordPress patch.

via GIPHY

Even more fun than rubber ducking is being the duck. Asking for a rubber duck in a team can feel like you’re being a burden. It’s an admission of, “I can’t figure this thing out.” We as devs take pride in how we can think through any sticky situation.

I have rubber ducked for some amazing developers at WebDevStudios. It’s easy to forget as rubber duck that your job is not to solve the issue. It’s to listen, empathize, ask questions, and relate.

I’ve seen issues in code in the first minute, and I’ve spent thirty minutes listening without understanding more than the cursory description of the problem, and everything in between. In all cases the rubber ducking was successful because the goal isn’t to jump in and solve the person’s programming issue. It’s to reset the approach and provide new perspective. There is no place for blame, pity, or frustration. It’s simply an opportunity to hack our human brains into being okay with… well… being human.

Normally, rubber ducking isn’t super time-consuming. A screen share starts, the dev with the problem frames it. The rubber duck may ask for some general background to get a mental model of the problem and then…

¯_(ツ)_/¯

Sidebar: I know we as devs aren’t supposed to be social. Writing code is usually a solitary endeavor. We all know that the final draft of our code has been wrestled with, refactored, and rewritten. When you duck or rubber duck, you are inserting two people into an incomplete thought. Be cognizant of the person behind the code. Sometimes it’s hard to remember that we are not our code.

rubber ducking is an amazing tool. It gives perspective; it resets our approach to a problem. It doesn’t indict or blame. Hopefully you have a great team of developers you can rubber duck with. If not, take to Twitter, your local meetup, or whatever social circle of technical people you have and agree to rubber duck for one another. Most importantly, set the example and be the rubber duck you’d want.


Photo by Andrew Wulf on Unsplash

The post Rubber Ducking appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2017/08/01/rubber-ducking/feed/ 1 17377
Winning With Code Reviews https://webdevstudios.com/2016/08/25/winning-code-reviews/ https://webdevstudios.com/2016/08/25/winning-code-reviews/#respond Thu, 25 Aug 2016 17:36:34 +0000 https://webdevstudios.com/?p=13339 Here at WebDevStudios we put a lot of emphasis on code quality. After handing off a product to a client, we never know who may be looking at and/or maintaining our code. We want to be proud and confident that the next person will not have an OMGWTFBBQ-head-smashing-into-keyboard moment, but one of delightful surprise. How Read More Winning With Code Reviews

The post Winning With Code Reviews appeared first on WebDevStudios.

]]>
Here at WebDevStudios we put a lot of emphasis on code quality. After handing off a product to a client, we never know who may be looking at and/or maintaining our code. We want to be proud and confident that the next person will not have an OMGWTFBBQ-head-smashing-into-keyboard moment, but one of delightful surprise.

How do we consistently create and maintain a high level of quality code? Through peer code reviews.

All developers at WebDevStudios are encouraged to request code reviews and to provide their own feedback to others on their code review requests.

Peer code reviews have enhanced the code quality at WebDevStudios by leaps and bounds. Now instead of coding in a hole, all the developers are actively striving to write good, clean code that will pass a code review the first time. Instead of feedback coming in the form of correction from a (busy) lead it has become a game amongst the developers to see who can write the most elegant and bug free code the first time out the gate. As a result, the coding standards and practices at WebDevStudios have grown and enhanced.

This all sounds good, but how does it work in practice?

When we receive a new project, it goes through an architecting phase that identifies all the key elements that will be required. These elements are then further broken down into their respective features. We utilize the Git code versioning system and its branching model to create a unique branch per feature, which we have detailed in a previous post titled An Alternative Git Flow for Client Work.

After a developer has finished a feature and before merging it back into the main branch, a code review is requested. Doing the code review at this step allows the reviewer to see all of the changes made on the feature branch compared to the main branch quite easily. The reviewer can then switch between branches to verify the feature code works and, if so desired, merge the feature into other branches to review against.

Reviews may be done by more than one other developer and have sometimes spurred incredible conversation and debate on the merits of performing an operation this way versus that way.

Code reviews promote healthy culture

As developers we are very proud of our code. Code is our form of art–where we express our inner Rembrandt. As such, critique of our artistry can be a stinging blow to our egos. I have seen instances where developers have nearly come to (virtual) blows when one suggests a change to the other’s code. Creating a healthy culture for code reviews counters any negative feelings that may arise.

We are all on the same team and we all have the same goal: To deliver the highest quality product to the client. When I was young my mother used to tell me, “If you do not have anything nice to say do not say anything at all.” We have applied the same motto to our code reviews. Feedback is never negative, but always constructive. By using positive language and helpfully showing each other new tricks and techniques, the skills of WDS devs have increased across the board and we have grown closer as a team.

Code reviews enhance security

Let’s admit it: All of us have written some code with a vulnerability issue. The most common of which is SQL injection points through unsanitized input. While coding, it is easy to become wrapped up in getting the feature done and lose sight of all the security implications of what you are writing. Having another set of eyes review the code can help to identify weaknesses.

This is further backed up by looking at a few of the major exploits that have been found in the WordPress ecosystem this year alone. Many of them were not found by probing the application, but by looking at the released source code and finding some place allowing unsecured input.

Code reviews increase social recognition and a feeling of self-worth

This may sound strange but there is powerful psychology behind code reviews. Providing code reviews causes us to feel good about helping out another, and receiving a code review that does not indicate anything needs to be updated in your code becomes almost a drug unto itself. Developers tend to amp up their game to “beat” the reviewers. Even us lead developers have our code reviewed, and I can tell you that nothing excites the team more than poking holes in code of the “best” developers on the team. (…Yeah, I had a code review only critiquing my use of white space…).

aziz ansari gif, code reviews, the importance of code reviews, why do code reviews, what is a code review, should lead developers do code reviews, how to do a code review, what's the point of a code review

Is it really worth the extra time?

When working on client projects time is of the essence, so we had to ask ourselves, “Is this worth the extra time it will take to develop a feature?”

The resounding answer is YES!

The increase in code quality and skills of the developers alone makes code reviews worth it, and the added benefit is finding bugs to be squashed well before being introduced in production.

According to a 2002 report by the National Institute of Standards and Technology a bug found post-production takes 18.7 hours to find and fix while a bug found during a code review takes just 3.2 hours to fix! That is 15.5 hours saved! What “extra time” are you worried about!?

Go forth and review thine code

As you can see, the idea behind code reviews is a simple one but it has BIG benefits. I want to encourage you to begin integrating code reviews into your workflow.

You may not have a team like we do here at WebDevStudios, but if you are reading this, you are part of the team of the community. WebDevStudios is just one fish in this pond that we call WordPress. Together, we are all striving to enhance this product that we use and love. Now get out there and start doing those code reviews!

I would love to hear about your experiences with code reviews in the comments and how your company or organization has implemented them.

The post Winning With Code Reviews appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2016/08/25/winning-code-reviews/feed/ 0 13339
The PHPStorm Debugger is Pretty Awesome https://webdevstudios.com/2016/06/21/phpstorm-debugger-awesome/ https://webdevstudios.com/2016/06/21/phpstorm-debugger-awesome/#comments Tue, 21 Jun 2016 17:17:34 +0000 https://webdevstudios.com/?p=13113 In a previous post, I wrote about how awesome PHPStorm is in the context of being a front-end developer. In this post, we are going to look at getting the PHPStorm debugger setup to work with Xdebug and then test it to make sure it’s working! In my opinion, one of the most overlooked and Read More The PHPStorm Debugger is Pretty Awesome

The post The PHPStorm Debugger is Pretty Awesome appeared first on WebDevStudios.

]]>
In a previous post, I wrote about how awesome PHPStorm is in the context of being a front-end developer. In this post, we are going to look at getting the PHPStorm debugger setup to work with Xdebug and then test it to make sure it’s working!

In my opinion, one of the most overlooked and underused features of PHPStorm is its debugger. I’ve only just recently started to learn about it and use it. One of the biggest reasons it is underused, even by developers who are already using PHPStorm, is because setting it up can be a confusing process if you’ve never done it before. Despite how it may appear, it’s very simple to setup, and once you do it a time or two, it’s something you can do in just a few short minutes.

The PHPStorm debugger will make you never want to use a var_dump() ever again!

I currently use Vagrant for my development environment which comes prepackaged with Xdebug. If you’re using something else like MAMP or XAMP, you’ll need to make sure you have Xdebug installed and activated.

Configure PHPStorm and Xdebug

In order for the PHPStorm debugger to work, it needs to be configured to work with Xdebug. Don’t be alarmed by the number of steps it takes to configure; I just wanted to be as detailed as possible.

1. In PHPStorm, go to Run > Edit Configurations. This brings up the Run/Debug Configurations window.
2. Click the + (top left) and select PHP Remote Debug from the drop-down to add a new config.

At this point, you should have a window that looks like this:
PHPStorm configuration
3. Click the ... next to Servers: so we can configure a server.
4. In the Servers dialog, click the + to add a new server configuration.
5. Enter in a Name and the Host address.
PHPStorm and Xdebug step 5
6. This step is for Vagrant users only. If you are not using Vagrant, please skip to step 7.

Click Use path mappings to configure file location settings. The File/Directory should already be preconfigured. Under Absolute path on server, you will need to enter in the path to your projects htdocs folder on your vagrant server. It should look something like this:
PHPStorm - Xdebug Path Mappings
7. Click Ok to save and close out the Servers dialog.
8. You should now be back at the Run/Debug Configurations dialog, but there should be a selection in the Servers: section with the server that was just configured.
9. Add in a Ide key(session id) of VVVDEBUG.
10. Check the checkbox for Single instance only.

The fully configured Run/Debug Configurations dialog should look like this:
xdebug-10
11. Click Ok to close and save everything out!

To recap:

  • Go to Run > Edit Configurations
  • Configure the server and the path mappings if you are using Vagrant
  • Give the configuration a name and set the Ide key to VVVDEBUG

See, it isn’t that bad after all!

The Big Test

Now that we have PHPStorm configured to work with Xdebug, it’s time to test it out and see if it is actually working. The debugger works like most others in that you’ll set a breakpoint in your code for investigation, and then reload the page. When the page reloads, PHPStorm will take over when the breakpoint is reached.

For this test, I’m going to add the following function to my functions.php file. It’s just a simple function that will merge two arrays using the nifty wp_parse_args() function.

Here’s what it looks like:

function test_debugger( $args ) {

    $defaults = array(
        'phpstorm' => 'Rocks!',
        'debugger' => false
    );

    $args = wp_parse_args( $args, $defaults );

    return $args;
}

// Call test_debugger
test_debugger( array(
    'var_dump' => 'no more',
    'debugger' => true
));

In my code, I’m going to set a breakpoint by clicking in the gutter at the exact spot where I want the debugger to kick in.
set-breakpoint

After the breakpoint is set, PHPStorm needs to be put into Debug Mode. This can be done by using Control + D or by going to Run > 'BPDefault' where ‘BPDefault’ is the name of the configuration created earlier.

After debugging is turned on, all that’s left is to reload the page and keep an eye on PHPStorm to work its magic!

Now, for the gif of all gifs:

Click on the image to view larger size.
Click on the image to view larger size.

There is a lot going on in this gif, so let me point out a few key points.

  • By pressing ^ (Control) + D the bottom Debug pane slides up. Then, I reload the page and PHPStorm kicks in where the breakpoint is set.
  • Notice the Variables column. It contains EVERY variable in scope at that time.
  • Then, I use the Step Into button to go into the test_debugger function.
  • As I’m stepping through, you can see the values of variables directly to the right of them.
  • Did you also catch that we stepped into the wp_parse_args()? Pretty cool stuff!
  • Finally, we can see in the Variables column that $args is set to the arrays that were merged.

Wrapping Up

A lot has been covered in this post and there is so much more that could be written about the different features the debugger provides. However, I think its best we save that for another post!

I’d also like to thank Kellen for sharing his knowledge with me on this subject.

If you find yourself getting stuck or not being able to get the debugger configured, please feel free to leave a question or comment below!

The post The PHPStorm Debugger is Pretty Awesome appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2016/06/21/phpstorm-debugger-awesome/feed/ 4 13113
Is Clever Code OK? https://webdevstudios.com/2016/05/17/is-clever-code-ok/ https://webdevstudios.com/2016/05/17/is-clever-code-ok/#respond Tue, 17 May 2016 15:53:22 +0000 https://webdevstudios.com/?p=12982 “Clever code” is a term that you may have heard before, accompanied by sighs and groans from other developers. Often, people seem to think of clever code as annoying, and perhaps even harmful. In this article, I’m going to give a brief overview of what clever code is, why it’s often avoided, and how it can Read More Is Clever Code OK?

The post Is Clever Code OK? appeared first on WebDevStudios.

]]>
“Clever code” is a term that you may have heard before, accompanied by sighs and groans from other developers. Often, people seem to think of clever code as annoying, and perhaps even harmful. In this article, I’m going to give a brief overview of what clever code is, why it’s often avoided, and how it can be turned into a learning experience.

What is “clever code?”

For most, clever code is code that does not immediately “explain” itself. What that means is that the average developer might see it and have to spend more than a few seconds reading the context around it to understand what it does. Here’s an example in PHP:

$foo = 'bar';
// snip
$value = $foo ?: false;

Considering I’ve been writing PHP for nearly sixteen years, I was bewildered when I first saw this in a co-worker’s code a few weeks ago.

“Pretty nifty, huh?”

You bet! I want to use that in the future, and it is a prime example of clever code–the slang of a programming language.

Opposition to clever code

If you’ve used clever code in the workplace, or in other projects where collaboration is a part of what you do, then you’ve probably run across a decent number of people who don’t like it. Some examples of feedback:

  • “So, why did you do it like this?”
  • “What am I looking at?”
  • “Don’t do that again.”

All very reasonable responses. Clever code is often cited as bringing a disadvantage beyond reading comprehension; it’s also viewed as a source of bugs. Implementing code that is harder to read means it’s more likely that you or a developer working in the same file later are more likely to not read the proper flow of the program. Here’s an example of using PHP’s Bitwise And operator:

// Bitwise And.
$foo = false;
$foo &= false;
$foo &= true;
$foo &= false;

var_dump( $foo ); // int(0)

$foo = false;
$foo &= false;
$foo &= true;

var_dump( $foo ); // int(0)

In the first example, you might expect the outcome of false, or “int(0)”. But the second example is a bit confusing–didn’t that end with setting $foo to true? The Bitwise And operator instead looks at both the left-hand value of “$foo” and the right-hand value when making its assignment; thus, if $foo is false even once, the equation will always look like “$foo = ( 0 * 1 = 0 = false ).” This can be extremely useful, but also incredibly confusing.

Another example of Bitwise confusion comes from the Javascript Bitwise NOT operator:

var a = ["f", "o", "o", "b", "a", "r" ];

if ( a.indexOf( "g" ) > -1 ) {
    console.log( "Typical style" );
}

if ( !!~a.indexOf( "g" ) ) {
    console.log( "Clever style" );
}

Again, we can see that the “tilde” operator, coupled with a double negative “!!”, creates clean code that won’t make sense to the average programmer.

How to be smart and clever

This all leads to what I’d like programmers to start doing when considering clever code: create a learning environment for other developers. I’ve seen clever solutions criticized on StackOverflow, and a particular question about it on the Programmer’s StackExchange asking for advice on how to avoid writing clever code in the first place. 

This, to me, is a great example of how programmers see clever code: it’s a party trick; it’s dangerous; it is to be avoided by “serious” programmers.

On the other hand, I think we can start to turn clever code into a learning experience. Once you recognize clever code, you can start to document it when you use it so others on the project know what you’re doing:

function check_user( $can_go_on ) {
    /**
     * NB, Clever: Using PHP's bitwise And operator.
     * See: http://php.net/manual/en/language.operators.bitwise.php
     */
    if ( ! current_user_can( 'manage_network' ) ) {
        $can_go_on &= false;
    }

    return $can_go_on;
}

function check_screen( $can_go_on ) {
    $screen = get_current_screen();

    if ( ! $screen || 'post' !== $screen->base ) {
        $can_go_on &= false;
    }

    return $can_go_on;
}

add_filter( 'can_we_continue', 'check_user' );
add_filter( 'can_we_continue', 'check_screen' );

$can_go_on = apply_filters( "can_we_continue", true );

In the above example, the ‘check_user’ function is documented to give a clear and distinct “Hey! I’m doing something weird here,” as opposed to the second method ‘check_screen’ which quietly uses the Bitwise And without any discussion. Most any programmer would be forgiven for missing it or thinking it’s a typo, and a scrutinizing lead would almost certainly see it and think “Great–now I have to change this and test everything this filter touches.”

A real world example looks like this:

/**
 * CLEVER CODE ALERT. This shorthand ternary accepts the tested value as the value returned if
 * true, otherwise the else value. NB this does not work in reverse (i.e. $a = $b ? 'value' :; ).
 */
$blog_id = $blog_id ?: get_current_blog_id();

Here’s that nifty shorthand ternary again! This saves some characters and looks pretty neat, but there’s a pretty hefty comment above it to explain what’s going on. The comment alone negates the time saved in not writing out the whole ternary, but for me the point of code like this, and the associated documentation, is to teach and inform others.

As programmers working in an increasingly collaborative world, we should be making strides in documentation–not only to guide other developers through the big ins and outs, but also to illuminate the many tricks and secrets that the language holds.

Happy coding!

The post Is Clever Code OK? appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2016/05/17/is-clever-code-ok/feed/ 0 12982