WordPress Core Architecture

Understanding the foundation and structure of the WordPress platform

Introduction to WordPress

WordPress is the world's most popular content management system (CMS), powering approximately 43% of all websites on the internet. Originally created in 2003 as a blogging platform, WordPress has evolved into a flexible, full-featured CMS suitable for building nearly any type of website—from blogs and portfolios to e-commerce stores and enterprise solutions.

The popularity of WordPress stems from several key factors:

At its core, WordPress balances simplicity with sophistication—making it accessible to beginners while providing powerful tools for developers. Understanding the WordPress architecture is essential for anyone looking to work with the platform beyond basic content management.

WordPress Core Components

WordPress can be viewed as a collection of integrated components that work together to create a cohesive system. Think of WordPress like a modern building with distinct but interconnected systems (electrical, plumbing, HVAC, etc.).

flowchart TB A[WordPress Core] --> B[Database] A --> C[File System] A --> D[Request Handling] B --> B1[MySQL/MariaDB] C --> C1[Themes] C --> C2[Plugins] C --> C3[Core Files] C --> C4[Media Library] D --> D1[Routing] D --> D2[Template Loading] D --> D3[The Loop] D --> D4[Hooks System] style A fill:#f96, stroke:#333, stroke-width:2px

The main components of WordPress include:

Database Layer

WordPress uses a MySQL or MariaDB relational database to store nearly all site content and settings. The database contains tables for posts, pages, comments, users, options, and metadata.

Real-world parallel: Think of the database as a filing cabinet where all your documents and records are stored in an organized manner.

Core Files

WordPress consists of PHP files that handle everything from database interactions to rendering content. These files make up the core functionality of WordPress.

Real-world parallel: These are like the essential systems of a building—plumbing, electrical, and structural components that enable basic functionality.

Theme System

Themes control the presentation of content, defining the visual design and layout of a WordPress site. Themes use a template hierarchy to determine which files are used to display different types of content.

Real-world parallel: Think of themes as the architectural style, interior design, and floor plan of a building—they define the appearance without changing the core structure.

Plugin Architecture

Plugins extend WordPress with additional functionality through a hook system that allows code to be executed at specific points during WordPress operation.

Real-world parallel: Plugins are like modular add-ons to a building—security systems, entertainment centers, or smart home features that extend functionality.

Administration Panel

The WordPress admin dashboard provides a user interface for managing content, settings, themes, plugins, and other aspects of a WordPress site.

Real-world parallel: This is the control center of the building, where systems can be monitored and adjusted without needing to access the underlying infrastructure.

REST API

WordPress includes a REST API that allows external applications to interact with WordPress data using standard HTTP methods.

Real-world parallel: Think of this as the building's external interfaces—doors, windows, and service connections that allow controlled access from the outside world.

The WordPress Database

The database is the foundation of WordPress, storing all content, settings, and structural information. A standard WordPress installation creates 12 default tables, each with a specific purpose:

erDiagram wp_posts ||--o{ wp_postmeta : has wp_posts ||--o{ wp_comments : receives wp_posts ||--o{ wp_term_relationships : belongs-to wp_comments ||--o{ wp_commentmeta : has wp_users ||--o{ wp_posts : creates wp_users ||--o{ wp_comments : writes wp_users ||--o{ wp_usermeta : has wp_terms ||--o{ wp_term_taxonomy : categorizes wp_term_taxonomy ||--o{ wp_term_relationships : connects

wp_posts

Stores all content including posts, pages, attachments, revisions, navigation menu items, and custom post types.

Key fields: ID, post_title, post_content, post_type, post_status, post_date

Example use case: When you create a new blog post, the content is stored in this table with a post_type of 'post'.

wp_postmeta

Contains metadata associated with posts, such as custom fields and settings.

Key fields: meta_id, post_id, meta_key, meta_value

Example use case: When using an SEO plugin, the meta description for a post is stored here.

wp_users

Stores user account information.

Key fields: ID, user_login, user_pass, user_email, user_registered

Example use case: When a new user registers, their account details are stored here.

wp_usermeta

Contains metadata associated with users, such as capabilities and preferences.

Key fields: umeta_id, user_id, meta_key, meta_value

Example use case: A user's role (administrator, editor, etc.) is stored here.

wp_comments

Stores comments made on posts and pages.

Key fields: comment_ID, comment_post_ID, comment_author, comment_content, comment_date

Example use case: When a visitor leaves a comment on a blog post, it's stored here.

wp_commentmeta

Contains metadata associated with comments.

Key fields: meta_id, comment_id, meta_key, meta_value

Example use case: A spam detection plugin might store spam score data here.

wp_terms

Stores categories, tags, and terms from custom taxonomies.

Key fields: term_id, name, slug

Example use case: When you create a new category like "Technology," it's stored here.

wp_term_taxonomy

Defines the taxonomy (category, tag, etc.) for terms in wp_terms.

Key fields: term_taxonomy_id, term_id, taxonomy, description

Example use case: This table specifies that "Technology" is a category taxonomy.

wp_term_relationships

Maps posts to terms, establishing relationships between content and categories/tags.

Key fields: object_id, term_taxonomy_id

Example use case: When you assign a post to the "Technology" category, that relationship is stored here.

wp_termmeta

Contains metadata associated with terms.

Key fields: meta_id, term_id, meta_key, meta_value

Example use case: If you add a custom icon to a category, that data might be stored here.

wp_options

Stores site-wide settings and options.

Key fields: option_id, option_name, option_value, autoload

Example use case: The site title, active theme, and plugin settings are stored here.

wp_links

An older table that previously stored blogroll links (rarely used in modern WordPress).

Example use case: This was used to manage links to other websites in early versions of WordPress.

WordPress uses a prefix (default "wp_") for all table names, which can be changed during installation for security purposes or to run multiple WordPress installations on a single database.

The database structure follows a flexible design pattern that allows WordPress to store diverse content types within the same tables. For example, posts, pages, and custom post types all use the wp_posts table, differentiated by the post_type field. This approach allows WordPress to maintain a relatively simple database schema while supporting complex content relationships.

WordPress File Structure

Understanding the WordPress file system organization is crucial for developers. A standard WordPress installation consists of the following directory structure:

wordpress/
├── wp-admin/          # Admin dashboard files
├── wp-content/        # User content (themes, plugins, uploads)
│   ├── plugins/       # Plugin files
│   ├── themes/        # Theme files 
│   └── uploads/       # Uploaded media files
├── wp-includes/       # Core functionality files
├── index.php          # Main entry point
├── wp-config.php      # Configuration file
└── [Other root files] # Various WordPress core files
          

wp-admin/

Contains all the files necessary for the WordPress admin dashboard.

Example files: index.php, admin.php, edit.php, post.php

Developer note: These files should never be modified. To customize admin functionality, use hooks from plugins instead.

wp-content/

The main directory for user-added content and customizations. This is where developers spend most of their time.

  • plugins/: Each plugin has its own subdirectory with PHP files, assets, and sometimes templates
  • themes/: Each theme has its own subdirectory with template files, assets, and functions.php
  • uploads/: Stores uploaded media files, organized by year and month
  • mu-plugins/: (optional) "Must-use" plugins that are automatically activated
  • languages/: (optional) Translation files for WordPress and its extensions

Developer note: This directory is preserved during WordPress updates, making it safe for customizations.

wp-includes/

Contains core WordPress files that provide functionality across the entire system.

Example files: functions.php, plugin.php, post.php, query.php, theme.php

Developer note: Never modify these files. They are replaced during WordPress updates and contain essential system code.

Root Files

Several important files reside in the WordPress root directory:

  • index.php: The main entry point for WordPress that loads the core system
  • wp-config.php: Contains database connection details and other configuration settings
  • wp-login.php: Handles user authentication
  • .htaccess: (on Apache servers) Contains server directives for permalinks and security
  • wp-*.php files: Various core files that handle specific functionality

Developer note: Of these files, only wp-config.php is meant to be edited directly in some cases.

This file structure follows a principle of separation: core WordPress files are kept separate from user content and customizations. This separation allows WordPress to be updated without overwriting custom themes and plugins, making the system more maintainable over time.

The WordPress Request Lifecycle

When a visitor accesses a WordPress site, a complex series of operations occurs to generate and deliver the appropriate content. Understanding this request lifecycle is essential for developers:

sequenceDiagram participant User participant Server participant Index as index.php participant WPCore as WP Core participant DB as Database participant Theme User->>Server: HTTP Request Server->>Index: Route Request Index->>WPCore: Bootstrap WordPress WPCore->>WPCore: Load wp-config.php WPCore->>DB: Connect to Database WPCore->>WPCore: Load Core Functions WPCore->>WPCore: Initialize Plugins WPCore->>WPCore: Parse Request WPCore->>DB: Query Content WPCore->>Theme: Load Template Theme->>User: Render HTML

Here's a detailed breakdown of what happens when a WordPress page is requested:

1. Initial Request

The browser sends an HTTP request to the web server.

Example: A visitor types https://example.com/sample-post/ in their browser.

2. Server Routing

The web server (Apache, Nginx, etc.) processes the request and routes it to WordPress.

What happens: The .htaccess file (on Apache) or server config directs the request to index.php.

3. WordPress Bootstrap

index.php loads wp-blog-header.php, which initiates the WordPress environment.

What happens: WordPress loads configuration, connects to the database, and sets up core functions.

4. Plugin Initialization

WordPress loads active plugins, which can hook into various parts of the request process.

What happens: Each plugin's main file is included, and initialization functions are executed.

5. Request Parsing

WordPress analyzes the URL to determine what content should be displayed.

What happens: The WP_Query class parses the URL and sets query variables.

Example: The URL /sample-post/ is recognized as a request for a single post with the slug "sample-post".

6. Content Query

WordPress queries the database to retrieve the requested content.

What happens: SQL queries are constructed based on the request type and executed against the database.

Example: WordPress retrieves the post with the slug "sample-post" from the wp_posts table.

7. Template Loading

WordPress determines which template file from the active theme should be used to display the content.

What happens: The template loader follows the Template Hierarchy to select the appropriate template file.

Example: For a single post, WordPress might use single.php or single-{post_type}.php.

8. Content Rendering

The selected template file generates HTML by combining theme markup with content from the database.

What happens: The Loop runs, processing each post or page returned by the query.

9. Final Output

The complete HTML is sent to the browser for display.

What happens: Filters can modify the output before it's delivered to the user.

Throughout this process, WordPress triggers numerous action and filter hooks, allowing plugins and themes to integrate with and modify every stage of content delivery. This hook-based architecture is what makes WordPress so extensible.

WordPress Core APIs

WordPress provides numerous Application Programming Interfaces (APIs) that allow developers to interact with various parts of the system. These APIs provide standardized ways to perform common operations:

Plugin API

Provides hooks (actions and filters) that allow plugins to modify WordPress behavior.

Key functions: add_action(), add_filter(), do_action(), apply_filters()

Example use:

// Add a function to the 'init' action hook
add_action('init', 'my_custom_init_function');

function my_custom_init_function() {
    // Code to run during WordPress initialization
    register_post_type('product', [...]);
}

// Filter content before display
add_filter('the_content', 'my_content_filter');

function my_content_filter($content) {
    // Modify $content in some way
    return $content . '<p>Thanks for reading!</p>';
}

Options API

Allows reading, writing, and managing site options/settings in the database.

Key functions: add_option(), get_option(), update_option(), delete_option()

Example use:

// Get an option with a default value if it doesn't exist
$option_value = get_option('my_plugin_setting', 'default_value');

// Update an option
update_option('my_plugin_setting', 'new_value');

// Add an option (only if it doesn't already exist)
add_option('my_plugin_setting', 'initial_value');

Metadata API

Manages metadata for posts, users, comments, and terms.

Key functions: add_post_meta(), get_post_meta(), update_post_meta(), delete_post_meta() (and similar for user, comment, and term)

Example use:

// Get post meta with a default value if it doesn't exist
$custom_field = get_post_meta($post_id, 'custom_field_name', true);

// Add post meta
add_post_meta($post_id, 'view_count', 1, true);

// Update post meta
update_post_meta($post_id, 'view_count', $new_count);

HTTP API

Provides a way to make HTTP requests to external APIs and services.

Key functions: wp_remote_get(), wp_remote_post(), wp_remote_request()

Example use:

// Make a GET request to an external API
$response = wp_remote_get('https://api.example.com/data');

// Check for errors
if (is_wp_error($response)) {
    // Handle error
} else {
    // Get response body
    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body);
    // Process data
}

Database API

Provides a safe way to interact with the WordPress database.

Key functions: $wpdb->insert(), $wpdb->update(), $wpdb->delete(), $wpdb->get_results()

Example use:

global $wpdb;

// Select data
$results = $wpdb->get_results(
    $wpdb->prepare(
        "SELECT * FROM {$wpdb->posts} WHERE post_type = %s AND post_status = %s",
        'post',
        'publish'
    )
);

// Insert data
$wpdb->insert(
    $wpdb->prefix . 'custom_table',
    [
        'column1' => 'value1',
        'column2' => 123
    ],
    ['%s', '%d']
);

Settings API

Standardizes the way plugin settings pages are created and managed.

Key functions: register_setting(), add_settings_section(), add_settings_field()

Shortcode API

Allows creating macros that can be used in post content to generate dynamic content.

Key functions: add_shortcode(), shortcode_atts(), do_shortcode()

Example use:

// Register a shortcode
add_shortcode('greeting', 'greeting_shortcode_function');

function greeting_shortcode_function($atts) {
    // Parse attributes with defaults
    $atts = shortcode_atts([
        'name' => 'World'
    ], $atts);
    
    // Return the shortcode output
    return '<p>Hello, ' . esc_html($atts['name']) . '!</p>';
}

// Usage in content: [greeting name="John"]

REST API

Provides HTTP endpoints for WordPress data, allowing external applications to interact with WordPress.

Key functions: register_rest_route(), WP_REST_Controller classes

Rewrite API

Manages URL rewriting for pretty permalinks.

Key functions: add_rewrite_rule(), add_rewrite_tag(), flush_rewrite_rules()

Widgets API

Enables the creation of widget areas and custom widgets.

Key functions: register_sidebar(), register_widget()

These APIs form the backbone of WordPress development, providing standardized interfaces for common operations. By using these APIs rather than directly manipulating the database or implementing custom solutions, developers ensure that their code is compatible with future WordPress updates and works well with other plugins and themes.

The Hooks System: Actions and Filters

The WordPress hooks system is the foundation of its extensibility. Hooks allow plugins and themes to modify WordPress behavior without editing core files, enabling the customization of almost any aspect of WordPress.

Think of hooks as events or interception points throughout the WordPress code. When WordPress runs, it reaches different points where it says, "If anyone wants to add or modify something here, now's your chance." Plugins and themes can register functions to run at these specific points.

graph TD A[WordPress Core Process] -->|Triggers| B[Hook] B -->|Executes| C[Plugin Function 1] B -->|Executes| D[Plugin Function 2] B -->|Executes| E[Theme Function] C --> A D --> A E --> A style B fill:#f96, stroke:#333, stroke-width:2px

There are two types of hooks in WordPress:

Actions

Action hooks allow you to add functionality at specific points in WordPress execution. They don't modify data but let you perform additional operations.

Metaphor: Think of actions like notifications. WordPress announces, "I'm about to save a post," and your plugin can say, "When that happens, I want to also do X."

Key functions:

  • add_action($hook_name, $callback, $priority, $accepted_args) - Register a function to an action
  • do_action($hook_name, $arg1, $arg2, ...) - Execute all functions registered to an action
  • remove_action($hook_name, $callback, $priority) - Remove a function from an action

Example:

// Register a function to run after a post is saved
add_action('save_post', 'my_function_after_save', 10, 3);

function my_function_after_save($post_id, $post, $update) {
    // Do something after a post is saved
    if ($update && $post->post_type == 'post') {
        // This is an update to an existing post
        update_post_meta($post_id, 'last_edited_time', time());
    }
}

Filters

Filter hooks allow you to modify data as it is processed. WordPress passes data through filters, allowing plugins to change it before it's used.

Metaphor: Think of filters like water filters. Water (data) flows through, and your filter can remove, add, or change things before it continues flowing.

Key functions:

  • add_filter($hook_name, $callback, $priority, $accepted_args) - Register a function to a filter
  • apply_filters($hook_name, $value, $arg1, ...) - Pass data through all functions registered to a filter
  • remove_filter($hook_name, $callback, $priority) - Remove a function from a filter

Example:

// Modify post content before display
add_filter('the_content', 'my_content_filter');

function my_content_filter($content) {
    // Add a call-to-action at the end of each post
    if (is_single() && !is_admin()) {
        $content .= '<div class="cta">Thanks for reading! Please subscribe to our newsletter.</div>';
    }
    return $content; // Always return the modified value
}

Common WordPress Hooks

WordPress includes hundreds of action and filter hooks. Here are some of the most commonly used:

Initialization Hooks

  • plugins_loaded - Action after all plugins are loaded
  • init - Action after WordPress has finished loading but before headers are sent
  • wp_loaded - Action after WordPress, all plugins, and the theme are fully loaded

Template & Display Hooks

  • wp_head - Action in the <head> section of the page
  • wp_footer - Action before the closing </body> tag
  • the_content - Filter for post/page content
  • the_title - Filter for post/page titles
  • template_include - Filter for the template file being loaded

Admin Hooks

  • admin_menu - Action for registering admin menu items
  • admin_init - Action on every admin page load
  • admin_enqueue_scripts - Action for loading admin scripts
  • admin_notices - Action for adding admin notifications

Post/Page Hooks

  • save_post - Action when a post or page is saved
  • pre_get_posts - Action to modify queries before they're executed
  • wp_insert_post_data - Filter for modifying post data before insertion
  • delete_post - Action when a post is deleted

User Hooks

  • user_register - Action when a user is registered
  • wp_login - Action when a user logs in
  • wp_authenticate_user - Filter for authenticating users
  • show_user_profile - Action for displaying user profile fields

Comment Hooks

  • comment_post - Action when a comment is inserted
  • pre_comment_approved - Filter for comment approval status
  • comment_text - Filter for comment text

The hooks system exemplifies WordPress's philosophy of extensibility. By providing hooks at virtually every significant point in the system's operation, WordPress allows developers to modify its behavior without touching core code. This makes updates safer, reduces conflicts between plugins, and allows for a modular approach to adding functionality.

Content Types and Taxonomies

WordPress provides a flexible content architecture that allows for various types of content to be managed through the same interface. This is achieved through post types and taxonomies:

Post Types

Post types are the different kinds of content WordPress can manage. By default, WordPress includes several built-in post types:

  • post - Standard blog posts
  • page - Static pages
  • attachment - Media files
  • revision - Post revisions
  • nav_menu_item - Navigation menu items

Developers can also create custom post types for specialized content such as products, events, testimonials, or any other content type needed for a specific website.

Example: Registering a Custom Post Type

// Register a custom post type for Events
function create_event_post_type() {
    register_post_type('event',
        array(
            'labels' => array(
                'name' => __('Events'),
                'singular_name' => __('Event')
            ),
            'public' => true,
            'has_archive' => true,
            'supports' => array('title', 'editor', 'thumbnail', 'excerpt'),
            'menu_icon' => 'dashicons-calendar',
            'rewrite' => array('slug' => 'events'),
        )
    );
}
add_action('init', 'create_event_post_type');

Taxonomies

Taxonomies are ways to classify and organize content. WordPress includes two built-in taxonomies:

  • category - Hierarchical classification for posts
  • tag - Non-hierarchical keywords for posts

Like post types, developers can create custom taxonomies to organize content in ways that match specific website needs.

Example: Registering a Custom Taxonomy

// Register a custom taxonomy for Event Types
function create_event_type_taxonomy() {
    register_taxonomy(
        'event_type',
        'event',
        array(
            'labels' => array(
                'name' => __('Event Types'),
                'singular_name' => __('Event Type')
            ),
            'hierarchical' => true, // Like categories
            'rewrite' => array('slug' => 'event-types'),
            'show_admin_column' => true,
        )
    );
}
add_action('init', 'create_event_type_taxonomy');

The post type and taxonomy system in WordPress provides a structured yet flexible way to manage content. This architecture allows WordPress to handle everything from simple blogs to complex content-driven websites with specialized content types and organizational systems.

Security Architecture

WordPress includes several built-in security features and follows security best practices in its architecture:

Database Abstraction

WordPress uses prepared SQL statements via the $wpdb class to prevent SQL injection attacks.

Good practice:

global $wpdb;
$results = $wpdb->get_results(
    $wpdb->prepare(
        "SELECT * FROM $wpdb->posts WHERE post_type = %s AND post_status = %s",
        'post',
        'publish'
    )
);

Bad practice (vulnerable to SQL injection):

global $wpdb;
// NEVER do this!
$status = $_GET['status']; // User input
$results = $wpdb->get_results(
    "SELECT * FROM $wpdb->posts WHERE post_status = '$status'"
);

Nonces (Number Used Once)

WordPress uses nonces to protect against CSRF (Cross-Site Request Forgery) attacks by ensuring that form submissions and ajax requests come from legitimate users.

Example:

// In a form:
wp_nonce_field('delete_post_' . $post_id, 'security');

// When processing the form:
if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'delete_post_' . $_POST['post_id'])) {
    die('Security check failed');
}

Capability System

WordPress uses a robust capability system to control what users can do based on their role.

Example:

// Check if user can edit posts
if (current_user_can('edit_posts')) {
    // Show edit link
}

// Check if user can edit a specific post
if (current_user_can('edit_post', $post_id)) {
    // Show edit link for this post
}

Data Validation and Sanitization

WordPress provides functions to sanitize and validate user input before use.

Common functions:

  • sanitize_text_field() - Sanitizes a text field
  • sanitize_email() - Sanitizes an email address
  • absint() - Converts to absolute integer
  • wp_kses() - Strips disallowed HTML
  • esc_html() - Escapes HTML entities
  • esc_url() - Escapes URLs
  • esc_attr() - Escapes HTML attributes

Example:

// Process form data safely
$name = sanitize_text_field($_POST['name']);
$email = sanitize_email($_POST['email']);
$content = wp_kses_post($_POST['content']); // Allow only safe HTML

// Output data safely
echo '<a href="' . esc_url($url) . '" title="' . esc_attr($title) . '">';
echo esc_html($name);
echo '</a>';

These security features are built into the WordPress core architecture, providing a foundation for secure web applications. However, security is a shared responsibility: plugin and theme developers must follow these practices in their own code, and website administrators must keep WordPress, plugins, and themes updated to protect against known vulnerabilities.

Practical Activity: Exploring WordPress Core

Let's solidify your understanding with a hands-on activity that explores the WordPress core architecture:

Activity: WordPress Core Structure Investigation

  1. Install a local WordPress environment using a tool like LocalWP, XAMPP, or Docker.
  2. Database Exploration:
    • Create a sample post, page, and category
    • Using phpMyAdmin or a similar tool, explore how this content is stored in the database
    • Find your post in wp_posts and observe the post_type field
    • Locate associated metadata in wp_postmeta
    • Find your category in wp_terms and wp_term_taxonomy
  3. Hook Investigation:
    • Create a simple plugin with this code:
    • <?php
      /**
       * Plugin Name: Hook Detective
       * Description: Logs when various hooks are fired
       */
      function log_hook($hook_name) {
          return function() use ($hook_name) {
              error_log("Hook fired: $hook_name");
          };
      }
      
      // Register our function to some common hooks
      add_action('plugins_loaded', log_hook('plugins_loaded'));
      add_action('init', log_hook('init'));
      add_action('wp_loaded', log_hook('wp_loaded'));
      add_action('wp_head', log_hook('wp_head'));
      add_action('wp_footer', log_hook('wp_footer'));
      add_action('the_content', function($content) {
          error_log("Hook fired: the_content");
          return $content;
      });
    • Activate the plugin and visit different pages of your site
    • Check your server's error log to see the hooks firing in sequence
  4. File Structure Analysis:
    • Navigate through the WordPress directory structure
    • Examine key files like index.php, wp-config.php, and wp-load.php
    • Look at some core files in wp-includes to see how functions are organized
  5. Additional Challenge: Use add_filter('template_include', function($template) { error_log("Template loaded: $template"); return $template; }); to see which template files are being used for different pages.

Summary and Key Takeaways

Understanding these core architectural concepts provides the foundation for effective WordPress development. In our next session, we'll explore how WordPress manages content through the post and page system.

Further Resources