WordPress Installation and Configuration

Setting up and optimizing WordPress environments for development and production

Introduction to WordPress Installation Options

WordPress can be installed in various environments to suit different needs, from local development to production websites. Understanding the various installation options helps you choose the right approach for your specific requirements.

Think of WordPress installation like setting up a workshop. You might need a temporary workspace for experimenting (local development), a collaborative space for team projects (staging), or a polished storefront for customers (production). Each serves a different purpose but contains similar tools.

Local Development Environment

A local installation runs WordPress on your own computer, allowing you to develop and test without affecting a live site.

Benefits:

  • Works offline without internet connection
  • Fast development with instant changes
  • Private testing environment for experimental changes
  • No impact on live sites during development

Common tools: LocalWP, XAMPP, MAMP, Docker, VirtualBox/Vagrant

Staging Environment

A staging site is a non-public copy of your production site used for testing changes before they go live.

Benefits:

  • Tests changes in an environment similar to production
  • Allows client review before changes go live
  • Can use real data (sanitized) for testing
  • Identifies potential issues before they affect users

Common approaches: Subdomain installation, hosting provider staging tools, duplicator plugins

Production Environment

The live public-facing WordPress installation that real users interact with.

Key considerations:

  • Performance optimization for real users
  • Security hardening to protect data
  • Backup systems for disaster recovery
  • Monitoring for uptime and issues

Common platforms: Traditional web hosting, managed WordPress hosting, cloud platforms (AWS, DigitalOcean)

graph TD A[WordPress Installations] --> B[Local Development] A --> C[Staging] A --> D[Production] B --> B1[LocalWP] B --> B2[XAMPP/MAMP] B --> B3[Docker] B --> B4[Vagrant] C --> C1[Subdomain] C --> C2[Hosting Provider Tools] C --> C3[Manual Clone] D --> D1[Shared Hosting] D --> D2[VPS/Dedicated] D --> D3[Managed WordPress] D --> D4[Cloud Platform] style A fill:#f96, stroke:#333, stroke-width:2px

For most development workflows, you'll want to use all three types of environments in sequence: developing and testing extensively in a local environment, then deploying to staging for client review or team testing, and finally pushing approved changes to production.

Setting Up a Local Development Environment

Local development environments allow you to build and test WordPress sites on your own computer. Let's explore several popular options:

LocalWP (formerly Local by Flywheel)

LocalWP is a user-friendly application specifically designed for WordPress development.

Key features:

  • One-click WordPress installation
  • Built-in Apache/Nginx, PHP, and MySQL
  • Easy site switching and management
  • SSL support for local sites
  • Live link sharing for client review
  • Blueprint feature for starter templates

Installation steps:

  1. Download LocalWP from https://localwp.com
  2. Install and launch the application
  3. Click "+ New Site" and follow the wizard
  4. Choose a site name, environment preferences, and admin credentials
  5. Access your new WordPress site with one click

Real-world analogy: LocalWP is like a pre-configured workshop that comes with all the tools already set up and organized—just walk in and start working.

XAMPP / MAMP / WAMP

These are general-purpose local server stacks (Apache, MySQL, PHP) for all kinds of web development.

Key features:

  • Cross-platform compatibility
  • Support for multiple PHP versions
  • Manual control over server settings
  • Can host multiple projects/technologies

WordPress installation with XAMPP:

  1. Download and install XAMPP
  2. Start Apache and MySQL services
  3. Download WordPress from wordpress.org
  4. Extract to htdocs folder (e.g., C:\xampp\htdocs\mysite)
  5. Create a database using phpMyAdmin (http://localhost/phpmyadmin)
  6. Navigate to http://localhost/mysite and follow the WordPress installation wizard

Real-world analogy: XAMPP is like setting up your own general-purpose workshop where you need to arrange the tools yourself but have more flexibility in how you configure the space.

Docker with WordPress

Docker provides container-based development environments that are consistent across different machines.

Key features:

  • Isolated environments with containers
  • Consistent setup across team members
  • Version-controlled environment configuration
  • Easy to replicate production settings

Basic WordPress Docker setup:

# Example docker-compose.yml file
version: '3'

services:
  db:
    image: mysql:5.7
    volumes:
      - db_data:/var/lib/mysql
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: somewordpress
      MYSQL_DATABASE: wordpress
      MYSQL_USER: wordpress
      MYSQL_PASSWORD: wordpress

  wordpress:
    depends_on:
      - db
    image: wordpress:latest
    ports:
      - "8000:80"
    restart: always
    volumes:
      - ./wp-content:/var/www/html/wp-content
    environment:
      WORDPRESS_DB_HOST: db:3306
      WORDPRESS_DB_USER: wordpress
      WORDPRESS_DB_PASSWORD: wordpress
      WORDPRESS_DB_NAME: wordpress

volumes:
  db_data: {}

To use this setup:

  1. Install Docker and Docker Compose
  2. Create a new directory for your project
  3. Create a docker-compose.yml file with the above content
  4. Run docker-compose up -d in that directory
  5. Access WordPress at http://localhost:8000

Real-world analogy: Docker is like having modular workshop pods that can be quickly assembled and disassembled, with guaranteed identical setups regardless of where you place them.

Vagrant with VVV (Varying Vagrant Vagrants)

VVV is a Vagrant configuration specifically designed for WordPress development.

Key features:

  • Complete development environment with testing tools
  • Support for multiple WordPress installations
  • Integration with WordPress core development
  • Advanced tools for theme/plugin development

Basic setup:

  1. Install VirtualBox and Vagrant
  2. Clone the VVV repository: git clone https://github.com/Varying-Vagrant-Vagrants/VVV.git
  3. Navigate to the directory and run vagrant up
  4. Access the default site at http://one.wordpress.test

Real-world analogy: VVV is like a professional-grade workshop with specialized tools for WordPress craftspeople, offering both basic and advanced equipment.

Choosing the right local environment: For beginners or those focused solely on WordPress, LocalWP offers the simplest experience. For developers who work with multiple technologies or need more control, XAMPP/MAMP/WAMP provide flexibility. Docker and Vagrant are ideal for team environments where consistent development setups are crucial.

The Famous 5-Minute WordPress Installation

WordPress is known for its simple installation process, often referred to as the "Famous 5-Minute Installation." Let's walk through this process, which applies to most hosting environments.

Prerequisites

  • Web server with PHP 7.4+ and MySQL 5.7+ or MariaDB 10.3+
  • PHP extensions: mysqli, xml, zip, gd/imagick, mbstring, exif
  • A database with username and password
  • FTP access or file manager (for traditional hosting)

Step-by-Step Installation

  1. Download WordPress

    Get the latest version from wordpress.org

  2. Upload the files

    Extract the WordPress files and upload them to your server's web directory (public_html, www, htdocs, etc.)

  3. Create the database

    Using phpMyAdmin or your hosting control panel, create a MySQL database and user with full privileges

    -- Example MySQL commands if using command line
    CREATE DATABASE wordpress;
    CREATE USER 'wordpressuser'@'localhost' IDENTIFIED BY 'password';
    GRANT ALL PRIVILEGES ON wordpress.* TO 'wordpressuser'@'localhost';
    FLUSH PRIVILEGES;
  4. Configure wp-config.php

    Rename wp-config-sample.php to wp-config.php and edit the database settings:

    // ** Database settings - You can get this info from your web host ** //
    /** The name of the database for WordPress */
    define( 'DB_NAME', 'wordpress' );
    
    /** Database username */
    define( 'DB_USER', 'wordpressuser' );
    
    /** Database password */
    define( 'DB_PASSWORD', 'password' );
    
    /** Database hostname */
    define( 'DB_HOST', 'localhost' );
    
    /** Database charset to use in creating database tables. */
    define( 'DB_CHARSET', 'utf8' );
    
    /** The database collate type. Don't change this if in doubt. */
    define( 'DB_COLLATE', '' );

    Also add the unique authentication keys and salts:

    /**#@+
     * Authentication unique keys and salts.
     * Generate these at: https://api.wordpress.org/secret-key/1.1/salt/
     */
    define( 'AUTH_KEY',         'put your unique phrase here' );
    define( 'SECURE_AUTH_KEY',  'put your unique phrase here' );
    define( 'LOGGED_IN_KEY',    'put your unique phrase here' );
    define( 'NONCE_KEY',        'put your unique phrase here' );
    define( 'AUTH_SALT',        'put your unique phrase here' );
    define( 'SECURE_AUTH_SALT', 'put your unique phrase here' );
    define( 'LOGGED_IN_SALT',   'put your unique phrase here' );
    define( 'NONCE_SALT',       'put your unique phrase here' );
  5. Run the installer

    Navigate to your site's URL in a web browser. You should see the WordPress setup wizard.

    Fill out the information:

    • Site title
    • Admin username (avoid "admin" for security)
    • Strong password
    • Admin email
    • Search engine visibility setting
  6. Complete installation

    Click "Install WordPress" and wait for confirmation.

    You can now log in with your username and password at yourdomain.com/wp-login.php

sequenceDiagram participant User participant Server participant DB as Database User->>Server: Upload WordPress files User->>DB: Create database User->>Server: Configure wp-config.php User->>Server: Access install.php Server->>DB: Test connection Server->>User: Show setup form User->>Server: Submit site information Server->>DB: Create tables Server->>DB: Insert initial data Server->>User: Installation complete

While this process is simple, many local development tools and hosting providers now offer one-click or automated WordPress installations that handle most of these steps for you.

WordPress in Production Environments

Moving beyond local development, let's explore setting up WordPress in production environments where performance, security, and reliability are critical concerns.

Shared Hosting

The most affordable option where your WordPress site shares server resources with many other websites.

Pros:

  • Cost-effective (typically $3-10/month)
  • Easy to use with cPanel or similar control panels
  • Managed MySQL databases
  • Often includes one-click WordPress installation

Cons:

  • Limited resources (can slow down during traffic spikes)
  • Potential security vulnerabilities from other sites on the server
  • Limited control over server configuration
  • Often lacks Git integration and deployment tools

Best for: Small websites, blogs, and low-traffic business sites with limited budgets

Virtual Private Server (VPS)

A virtual server that provides dedicated resources and greater control.

Pros:

  • Dedicated resources (CPU, RAM, storage)
  • Root access for custom configurations
  • Better isolation from other websites
  • Scalable resources as needs grow

Cons:

  • Requires more technical knowledge to manage
  • More expensive than shared hosting ($20-100/month)
  • Responsibility for security updates and maintenance

Best for: Medium-sized business websites, online stores, and sites that need custom server configurations

Managed WordPress Hosting

Specialized hosting optimized specifically for WordPress sites.

Pros:

  • WordPress-specific optimizations for speed
  • Automatic WordPress core updates
  • Enhanced security measures
  • Built-in caching solutions
  • Specialized WordPress support
  • Often includes staging environments

Cons:

  • Higher cost than general hosting ($25-200+/month)
  • Restrictions on certain plugins (for security/performance)
  • Less flexibility for non-WordPress applications

Best for: Business-critical WordPress sites, high-traffic blogs, and e-commerce stores

Popular providers: WP Engine, Kinsta, Flywheel, Pantheon

Cloud Hosting Platforms

Infrastructure-as-a-service platforms where you can deploy WordPress on scalable cloud resources.

Pros:

  • Highly scalable (can handle traffic spikes)
  • Pay-as-you-go pricing model
  • Global availability and redundancy
  • Complete control over the environment
  • Advanced deployment options

Cons:

  • Requires DevOps knowledge to set up properly
  • Responsibility for all server management
  • Can become expensive with high traffic

Best for: Enterprise websites, applications with variable traffic, and organizations with DevOps teams

Popular platforms: AWS, Google Cloud Platform, DigitalOcean, Linode

WordPress-Specific Server Requirements

For optimal WordPress performance in production, ensure your server meets or exceeds these recommendations:

You can check your server's compatibility with WordPress using a plugin like Health Check & Troubleshooting or by visiting the Site Health page in WordPress admin (Tools → Site Health).

Essential WordPress Configuration Options

WordPress offers numerous configuration options that affect how your site functions. Let's explore the most important settings you should configure.

WordPress Address (URL) and Site Address (URL)

Found in Settings → General, these URLs define where WordPress files are located and how your site is accessed.

WordPress Address (URL): The location of your core WordPress files

Site Address (URL): The address users type to visit your site

In most cases, these are the same. However, they can differ when WordPress is installed in a subdirectory but accessed from the root domain.

Example in wp-config.php:

define('WP_HOME', 'https://example.com');
define('WP_SITEURL', 'https://example.com/wp');

Real-world analogy: Think of WordPress Address as the location of your company's headquarters, and Site Address as your customer-facing storefront address.

Permalink Settings

Found in Settings → Permalinks, this controls the URL structure of your posts and pages.

Options include:

  • Plain: ?p=123 (not recommended for SEO)
  • Day and name: /2023/05/sample-post/
  • Month and name: /2023/05/sample-post/
  • Numeric: /archives/123
  • Post name: /sample-post/ (most commonly used)
  • Custom Structure: Define your own with available tags

Notes: Changing permalinks after your site has been indexed by search engines can affect SEO. Apache requires mod_rewrite and .htaccess files, while Nginx needs specific server configurations.

Database Configuration

Beyond the basic connection settings, wp-config.php offers several database options:

// Database table prefix
$table_prefix = 'wp_';

// Database character set
define('DB_CHARSET', 'utf8mb4');
define('DB_COLLATE', 'utf8mb4_unicode_ci');

// Custom database connection
define('DB_HOST', '127.0.0.1:3306');
// Or separate read/write servers:
define('DB_HOST', 'write-db.example.com:3306;read-db.example.com:3306');

Best practice: For security, always change the default table prefix (wp_) to something unique when setting up a new site.

Security Keys and Salts

These random values in wp-config.php strengthen authentication cookies and passwords.

define('AUTH_KEY',         'randomly generated string');
define('SECURE_AUTH_KEY',  'randomly generated string');
define('LOGGED_IN_KEY',    'randomly generated string');
define('NONCE_KEY',        'randomly generated string');
define('AUTH_SALT',        'randomly generated string');
define('SECURE_AUTH_SALT', 'randomly generated string');
define('LOGGED_IN_SALT',   'randomly generated string');
define('NONCE_SALT',       'randomly generated string');

Best practice: Generate unique values using the WordPress.org secret-key service and change them periodically for enhanced security.

Debug Settings

Control error display and logging in WordPress:

// Enable debugging (development environments only)
define('WP_DEBUG', true);

// Log errors instead of displaying them
define('WP_DEBUG_LOG', true);

// Disable display of errors to users
define('WP_DEBUG_DISPLAY', false);

// Disable JavaScript and CSS concatenation (for debugging)
define('SCRIPT_DEBUG', true);

Best practice: Enable WP_DEBUG in development environments but never in production. In production, use WP_DEBUG_LOG but disable WP_DEBUG_DISPLAY.

Memory and Performance Settings

Adjust resource allocation and caching behaviors:

// Increase PHP memory limit for WordPress
define('WP_MEMORY_LIMIT', '256M');

// Increase memory for admin area
define('WP_MAX_MEMORY_LIMIT', '512M');

// Enable page caching
define('WP_CACHE', true);

// Disable post revisions or limit them
define('WP_POST_REVISIONS', false); // or define('WP_POST_REVISIONS', 3);

// Set autosave interval (in seconds)
define('AUTOSAVE_INTERVAL', 160);

// Disable file editing in admin
define('DISALLOW_FILE_EDIT', true);

Note: Some settings may be overridden by host configurations or may not work on all hosting environments.

Multisite Configuration

WordPress can run multiple websites from a single installation:

// Enable WordPress Multisite
define('WP_ALLOW_MULTISITE', true);

// After running the Network Setup:
define('MULTISITE', true);
define('SUBDOMAIN_INSTALL', true); // or false for subdirectory
define('DOMAIN_CURRENT_SITE', 'example.com');
define('PATH_CURRENT_SITE', '/');
define('SITE_ID_CURRENT_SITE', 1);
define('BLOG_ID_CURRENT_SITE', 1);

Use case: Multisite is ideal for managing multiple related websites, such as university departments, franchise locations, or multilingual sites.

Environment-Specific Configuration

Modern WordPress development often uses different settings based on the environment:

// Define environment
define('WP_ENVIRONMENT_TYPE', 'development'); // 'development', 'staging', or 'production'

// Example environment-specific settings
if (defined('WP_ENVIRONMENT_TYPE')) {
    if (WP_ENVIRONMENT_TYPE === 'development') {
        define('WP_DEBUG', true);
        define('WP_DEBUG_LOG', true);
        define('WP_DEBUG_DISPLAY', true);
        define('SCRIPT_DEBUG', true);
    } elseif (WP_ENVIRONMENT_TYPE === 'staging') {
        define('WP_DEBUG', true);
        define('WP_DEBUG_LOG', true);
        define('WP_DEBUG_DISPLAY', false);
        define('DISALLOW_INDEXING', true);
    } elseif (WP_ENVIRONMENT_TYPE === 'production') {
        define('WP_DEBUG', false);
        define('DISALLOW_FILE_EDIT', true);
        define('DISALLOW_FILE_MODS', true);
    }
}

Best practice: Use a configuration approach that keeps sensitive data (like database credentials) out of version control. Tools like wp-config-transformer or environment variables can help with this.

WordPress Security Essentials

Security is critical for any WordPress installation. Here are essential configurations and best practices to protect your WordPress site:

Secure WordPress Configuration

  • Use HTTPS

    Install an SSL certificate and force HTTPS for all requests:

    // In wp-config.php
    define('FORCE_SSL_ADMIN', true);
    
    // Optionally, force SSL for all WordPress content
    if ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')
        $_SERVER['HTTPS'] = 'on';
  • Disable File Editing in Admin

    Prevent plugin and theme editing within WordPress:

    define('DISALLOW_FILE_EDIT', true);
  • Protect wp-config.php

    Block direct access to wp-config.php with an .htaccess rule:

    # Block access to wp-config.php
    <files wp-config.php>
    order allow,deny
    deny from all
    </files>
  • Change Database Prefix

    Avoid the default "wp_" prefix to prevent SQL injection attacks:

    $table_prefix = 'unique_prefix_';
  • Disable XML-RPC if Not Used

    Add this to your .htaccess file if you don't use XML-RPC:

    # Block WordPress xmlrpc.php requests
    <Files xmlrpc.php>
    order deny,allow
    deny from all
    </Files>
  • Hide WordPress Version

    Remove the WordPress version from HTML and feeds:

    // Add to functions.php
    function remove_version_info() {
        return '';
    }
    add_filter('the_generator', 'remove_version_info');

Secure Login Practices

  • Use Strong Admin Credentials

    Create a unique username (not "admin") and a strong password

  • Implement Two-Factor Authentication

    Use a plugin like Two Factor Authentication or Wordfence

  • Limit Login Attempts

    Add protection against brute force attacks with plugins like Limit Login Attempts Reloaded

  • Change the Login URL

    Hide the default wp-login.php with a plugin like WPS Hide Login

File and Folder Permissions

Set proper permissions to prevent unauthorized file access:

  • Directories: 755 (drwxr-xr-x)
  • Files: 644 (rw-r--r--)
  • wp-config.php: 600 (rw-------)
# Fix permissions using SSH
find /path/to/wordpress -type d -exec chmod 755 {} \;
find /path/to/wordpress -type f -exec chmod 644 {} \;
chmod 600 /path/to/wordpress/wp-config.php

Regular Updates

Keep all components updated to protect against known vulnerabilities:

  • WordPress core updates
  • Theme updates
  • Plugin updates
  • PHP and MySQL updates

Best practice: Set up automated update alerts and regular maintenance schedules.

Backup Strategy

Implement a robust backup system in case of security breaches:

  • Regular backups of all WordPress files
  • Regular database backups
  • Store backups in multiple locations
  • Test backup restoration process

Tools: UpdraftPlus, BackupBuddy, or managed hosting backup solutions

Security Plugins

Consider using security plugins for comprehensive protection:

  • Wordfence: Firewall, malware scanner, and login security
  • Sucuri Security: Security auditing, monitoring, and hardening
  • iThemes Security: 30+ ways to secure WordPress
  • MalCare: Malware scanning with safe cleanup

Note: Security plugins can sometimes conflict with each other or impact performance. Generally, choose one comprehensive solution rather than multiple security plugins.

Security is an ongoing process, not a one-time setup. Regularly audit your WordPress installation, review logs for suspicious activity, and stay informed about new security threats and patches.

Performance Optimization for WordPress

A well-optimized WordPress site loads quickly, ranks better in search engines, and provides a better user experience. Here are essential performance optimization strategies:

Server-Level Optimization

  • Use PHP 8.0+

    The latest PHP versions offer significant performance improvements over older versions.

  • Implement Caching

    Server-level caching solutions like Redis, Memcached, or OPcache can dramatically improve performance.

  • Use HTTP/2 or HTTP/3

    Modern HTTP protocols allow for faster loading of multiple resources.

  • Enable Gzip Compression

    Compress files before sending them to the browser:

    # Apache (.htaccess)
    <IfModule mod_deflate.c>
      AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript application/x-javascript
    </IfModule>
    
    # Nginx (nginx.conf)
    gzip on;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
  • Implement Content Delivery Network (CDN)

    Distribute static assets across global servers to reduce latency.

WordPress Configuration Optimization

  • Enable Object Caching

    Implement persistent object caching to reduce database queries:

    // Example for Redis object cache in wp-config.php
    define('WP_CACHE', true);
    define('WP_REDIS_HOST', '127.0.0.1');
    define('WP_REDIS_PORT', '6379');
  • Optimize Database

    Regularly clean and optimize the WordPress database:

    • Remove post revisions: define('WP_POST_REVISIONS', 3);
    • Increase autosave interval: define('AUTOSAVE_INTERVAL', 300);
    • Run optimization queries or use plugins like WP-Optimize
  • Disable Unused Features

    Turn off WordPress features you don't use:

    // Disable Emoji support
    remove_action('wp_head', 'print_emoji_detection_script', 7);
    remove_action('wp_print_styles', 'print_emoji_styles');
    
    // Disable XML-RPC
    add_filter('xmlrpc_enabled', '__return_false');
    
    // Disable pingbacks
    add_filter('xmlrpc_methods', function($methods) {
        unset($methods['pingback.ping']);
        return $methods;
    });
    
    // Disable embeds
    function disable_embeds() {
        remove_action('wp_head', 'wp_oembed_add_discovery_links');
        remove_action('wp_head', 'wp_oembed_add_host_js');
        // Additional embed disabling...
    }
    add_action('init', 'disable_embeds', 9999);

Frontend Optimization

  • Optimize Images

    Properly size and compress images before uploading:

    • Use modern formats like WebP where supported
    • Implement lazy loading for images
    • Use image optimization plugins like Smush or ShortPixel
  • Minify and Combine Assets

    Reduce the size and number of CSS and JavaScript files:

    • Minify CSS and JavaScript files
    • Combine multiple files where appropriate
    • Use plugins like Autoptimize or WP Rocket
  • Implement Critical CSS

    Inline critical styles in the head and defer non-critical CSS loading.

  • Defer JavaScript Loading

    Prevent render-blocking JavaScript:

    function defer_js_files($tag, $handle, $src) {
        if ( !is_admin() ) {
            // Add the defer attribute to these scripts
            $scripts_to_defer = array('jquery-core', 'my-script-handle');
            
            foreach($scripts_to_defer as $defer_script) {
                if ($defer_script === $handle) {
                    return str_replace(' src', ' defer src', $tag);
                }
            }
        }
        return $tag;
    }
    add_filter('script_loader_tag', 'defer_js_files', 10, 3);
  • Use Prefetch and Preconnect

    Improve loading performance with resource hints:

    function add_resource_hints($hints, $relation_type) {
        if ('preconnect' === $relation_type) {
            // Add preconnect for Google Fonts
            $hints[] = [
                'href' => 'https://fonts.googleapis.com',
                'crossorigin' => 'anonymous',
            ];
            $hints[] = [
                'href' => 'https://fonts.gstatic.com',
                'crossorigin' => 'anonymous',
            ];
        }
        return $hints;
    }
    add_filter('wp_resource_hints', 'add_resource_hints', 10, 2);

Caching Plugins

Implement a caching plugin to generate static HTML files:

  • WP Rocket: Premium all-in-one caching and optimization
  • W3 Total Cache: Comprehensive caching with many configuration options
  • WP Super Cache: Simpler caching solution by Automattic
  • LiteSpeed Cache: Advanced caching for LiteSpeed servers

Key caching features to enable:

  • Page caching
  • Browser caching
  • Object caching (if available)
  • Database query caching
  • CSS and JavaScript optimization

Monitoring Performance

Regularly test your WordPress site's performance:

  • Google PageSpeed Insights: Measures performance and provides optimization suggestions
  • GTmetrix: Detailed performance reports and recommendations
  • WebPageTest: Advanced testing from multiple locations and browsers
  • Query Monitor: WordPress plugin to identify slow queries and plugins
  • New Relic: Application performance monitoring

Best practice: Establish performance budgets and regularly check that your site meets them.

Performance optimization is an ongoing process. As your WordPress site grows and evolves, you'll need to continually monitor and improve performance to maintain a fast, responsive user experience.

Practical Activity: WordPress Environment Setup

Let's put our knowledge into practice with a hands-on activity that walks through setting up a complete WordPress development environment:

Activity: Setting Up a Development-to-Production Workflow

Part 1: Local Development Environment

  1. Install LocalWP
    • Download and install LocalWP from localwp.com
    • Create a new WordPress site with the following settings:
      • Site Name: "Project Portfolio"
      • Environment: Custom with PHP 8.0, MySQL 8.0
      • Username: Choose something other than "admin"
      • Enable "Add WP-CLI support"
    • Start the site and access the WordPress admin
  2. Optimize wp-config.php for Development
    • Enable debugging: define('WP_DEBUG', true);
    • Log errors: define('WP_DEBUG_LOG', true);
    • Show errors: define('WP_DEBUG_DISPLAY', true);
    • Set environment: define('WP_ENVIRONMENT_TYPE', 'development');
  3. Set Up Version Control
    • Initialize a Git repository in the site's root directory
    • Create a .gitignore file with:
      # WordPress core files
      wp-admin/
      wp-includes/
      wp-content/upgrade/
      wp-content/uploads/
      index.php
      license.txt
      readme.html
      wp-*.php
      xmlrpc.php
      
      # Configuration
      wp-config.php
      
      # Log files
      *.log
      wp-content/debug.log
      
      # Dependency directories
      node_modules/
      vendor/
      
      # Cache and temporary files
      wp-content/cache/
      wp-content/backup-db/
      wp-content/advanced-cache.php
      wp-content/wp-cache-config.php
      wp-content/uploads/
      wp-content/upgrade/
      
      # Environment specific files
      .env
      .env.*
      !.env.example
    • Create a wp-config-sample.php with sensitive information removed
    • Make an initial commit of your WordPress files

Part 2: Staging Environment Setup

  1. Create a Staging Site
    • If using managed hosting: Use the host's staging creation feature
    • If using traditional hosting:
      • Create a subdomain (e.g., staging.example.com)
      • Set up a new WordPress installation
      • Configure the staging database
  2. Configure wp-config.php for Staging
    • Set environment: define('WP_ENVIRONMENT_TYPE', 'staging');
    • Enable debugging but disable display: define('WP_DEBUG', true); define('WP_DEBUG_LOG', true); define('WP_DEBUG_DISPLAY', false);
    • Prevent indexing: define('DISALLOW_INDEXING', true);
    • Limit access: Set up basic HTTP authentication for the staging site
  3. Set Up Deployment
    • Configure Git branches (develop, staging, main)
    • Set up a deployment method (Git push, SFTP, deployment plugin, or CI/CD)
    • Create a deployment script or workflow

Part 3: Production Configuration

  1. Security Hardening
    • Configure security settings in wp-config.php:
      // Security settings
      define('DISALLOW_FILE_EDIT', true);
      define('DISALLOW_FILE_MODS', true);
      define('FORCE_SSL_ADMIN', true);
      
      // Performance settings
      define('WP_POST_REVISIONS', 5);
      define('AUTOSAVE_INTERVAL', 160);
      
      // Environment
      define('WP_ENVIRONMENT_TYPE', 'production');
    • Set up proper file permissions
    • Configure SSL certificate
    • Install a security plugin
  2. Performance Optimization
    • Install and configure a caching plugin
    • Set up browser caching with .htaccess rules
    • Configure a CDN for static assets
    • Optimize the database
  3. Monitoring and Maintenance
    • Set up automated backups
    • Configure uptime monitoring
    • Create a maintenance plan for updates and monitoring
    • Run a performance test with PageSpeed Insights

Extension Challenge: Multi-Environment Configuration

Create a more sophisticated environment configuration system:

  1. Create a wp-config.php that loads environment-specific settings from separate files
  2. Implement environment detection based on server variables or domain names
  3. Use environment variables for sensitive data instead of hardcoding
  4. Set up different error logging levels for each environment

Migrating WordPress Sites

Migrating WordPress sites between environments is a common task in the development process. Here are the key methods and best practices:

Manual Migration

Step-by-step process for moving WordPress sites:

  1. Backup the existing site
    • Export the database using phpMyAdmin or WP-CLI
    • Download all WordPress files via FTP
  2. Prepare the new environment
    • Create a new database and user
    • Upload WordPress files to the new server
  3. Update wp-config.php
    • Update database connection details
    • Change environment-specific settings
  4. Import the database
    • Using phpMyAdmin, command line, or hosting tools
    • Search and replace URLs in the database (critical step)
  5. Update file paths and permalinks
    • Check for hardcoded URLs in theme files
    • Flush permalinks by visiting Settings → Permalinks
  6. Test the migrated site
    • Check all major functionality
    • Look for broken images or links
    • Test forms and interactive elements

Search & Replace Tool: When migrating a database, always use a proper search and replace tool like WP-CLI or the Interconnect/it Database Search and Replace Script rather than direct SQL queries to handle serialized data correctly.

Migration Plugins

Several plugins simplify the migration process:

  • Duplicator

    Creates a complete site package (files and database) that can be installed on a new server with a simple installer script.

  • All-in-One WP Migration

    Export/import your entire site to a file that can be imported on another WordPress installation.

  • WP Migrate DB Pro

    Powerful plugin for database migrations with push/pull capabilities between environments.

  • BackupBuddy

    Creates complete backups that can be used for migration.

Plugin workflow example (Duplicator):

  1. Install Duplicator on the source site
  2. Create a package (archive + installer)
  3. Upload both files to the new server
  4. Run the installer.php script
  5. Follow the wizard to complete the migration

Using WP-CLI

WP-CLI offers powerful commands for migrating WordPress sites:

# Export database
wp db export database.sql

# Import database on new server
wp db import database.sql

# Search and replace URLs in the database
wp search-replace 'http://olddomain.com' 'http://newdomain.com' --all-tables

# Export/import content with WXR
wp export
wp import exported-content.xml --authors=create

# Install WordPress (on fresh server)
wp core download
wp config create --dbname=dbname --dbuser=username --dbpass=password
wp core install --url=example.com --title="Site Title" --admin_user=admin --admin_password=password --admin_email=admin@example.com

Advantages of WP-CLI migration:

  • Scriptable and automatable
  • Works well with version-controlled projects
  • Efficient for large sites
  • Can be integrated into CI/CD pipelines

Hosting Provider Tools

Many WordPress hosting providers offer built-in migration tools:

  • WP Engine: Automated migration plugin
  • Kinsta: One-click migrations from dashboard
  • SiteGround: WordPress migrator tool
  • Flywheel: Free migration service
  • DreamHost: Automated WordPress migration

Benefits: These tools are often optimized for the host's specific environment and may handle complicated configurations automatically.

Migration Best Practices

Migration is a critical operation that requires careful planning and execution. By following these methods and best practices, you can ensure smooth transitions between environments with minimal disruption.

Summary and Key Takeaways

Understanding WordPress installation and configuration is fundamental for developing and maintaining effective WordPress websites. By properly setting up your environments and implementing best practices for security and performance, you lay the groundwork for successful WordPress development.

Further Resources