Dev.to Security 🔐 Cybersecurity 👁 0 📖 5 min read

WordPress Security Internals: Hooks, Nonces and Filters

Understanding how WordPress core handles authentication and sanitization. WordPress powers millions of websites through its flexible themes, plugins and REST API. However, this flexibility also creates security challeng

Understanding how WordPress core handles authentication and sanitization.

WordPress powers millions of websites through its flexible themes, plugins and REST API. However, this flexibility also creates security challenges when developers write custom functionality without following secure coding practices.

A small mistake in a plugin or theme can expose sensitive information, allow unauthorized actions or introduce vulnerabilities such as SQL Injection (SQLi) and Cross-Site Scripting (XSS).

Understanding how WordPress core handles authentication and sanitization is essential for writing secure custom themes and plugins without introducing SQLi or XSS.

This guide explores WordPress hooks, nonces, filters, database queries and practical security testing techniques that developers can apply to real projects.

1. Understanding WordPress Hooks: Actions and Filters

Hooks are one of the most important parts of WordPress architecture. They allow developers to interact with WordPress core without modifying its original files.

WordPress provides two main types of hooks:

  • Actions: Execute custom functionality at specific points during WordPress execution.
  • Filters: Modify data before it is returned, displayed or processed.

For example, an action can execute code when a plugin loads, while a filter can modify content before it appears on a website.

Example: Using an Action Hook

add_action('init', function () {
    error_log('Custom security plugin initialized.');
});

This executes when WordPress initializes.

Example: Using a Filter Hook

add_filter('the_content', function ($content) {

    return $content . '<p>Security information updated.</p>';

});

This modifies post content before it is displayed.

Developers should remember that filters do not automatically make data safe. Output must still be escaped according to its context.

2. WordPress Nonces and Authentication Security

A nonce is a security token used by WordPress to help protect against Cross-Site Request Forgery (CSRF).

It verifies that a request contains a valid token associated with a particular action and user context.

However, a nonce is not a replacement for authentication or authorization.

Vulnerable approach:

if (isset($_POST['delete_item'])) {
    wp_delete_post($_POST['delete_item'], true);
}

This code processes a deletion request without checking the user's capability or verifying a nonce.

Remediated approach:

if (isset($_POST['delete_item'])) {

    check_admin_referer('delete_item_action');

    $post_id = absint(
        wp_unslash($_POST['delete_item'])
    );

    if (!current_user_can('delete_post', $post_id)) {
        wp_die('Unauthorized request.');
    }

    wp_delete_post($post_id, true);
}

The improved implementation:

  • Verifies the request nonce.
  • Converts the supplied post ID into an integer.
  • Checks whether the current user can delete that particular post.
  • Performs the operation only after security checks pass.

This approach reduces the risk of unauthorized deletion and CSRF attacks.

3. Preventing SQL Injection and XSS in Custom Plugins

SQL Injection happens when untrusted input is inserted into database queries without proper handling.

Consider this vulnerable example:

Vulnerable SQL query:

global $wpdb;

$user_id = $_GET['id'];

$query = "SELECT * FROM {$wpdb->users}
          WHERE ID = $user_id";

$results = $wpdb->get_results($query);

Directly inserting request data into a SQL query can introduce SQL injection vulnerabilities.

Remediated SQL query:

global $wpdb;

$user_id = isset($_GET['id'])
    ? absint(wp_unslash($_GET['id']))
    : 0;

$query = $wpdb->prepare(
    "SELECT * FROM {$wpdb->users}
     WHERE ID = %d",
    $user_id
);

$results = $wpdb->get_results($query);

Using $wpdb->prepare() ensures that the supplied value is handled as a parameter rather than being directly inserted into the SQL statement.

Preventing Cross-Site Scripting (XSS)

XSS occurs when untrusted data is displayed in a browser without appropriate output escaping.

Vulnerable example:

echo $_GET['name'];

Remediated example:

$name = isset($_GET['name'])
    ? sanitize_text_field(
        wp_unslash($_GET['name'])
    )
    : '';

echo esc_html($name);

WordPress provides different escaping functions for different contexts:

  • esc_html() – HTML text.
  • esc_attr() – HTML attributes.
  • esc_url() – URLs.
  • wp_kses_post() – Permitted post HTML.

Sanitization and escaping serve different purposes. Sanitize incoming data according to its intended use and escape it when displaying it.

4. Securing WordPress REST API Endpoints

Custom REST API endpoints can expose sensitive functionality when authentication and authorization are not implemented correctly.

WordPress allows developers to register custom routes using register_rest_route().

Vulnerable implementation:

add_action('rest_api_init', function () {

    register_rest_route('custom/v1', '/profile', [
        'methods' => 'POST',

        'callback' => function ($request) {

            return [
                'name' => $request->get_param('name')
            ];
        }
    ]);

});

The endpoint does not define an explicit permission callback.

Remediated implementation:

add_action('rest_api_init', function () {

    register_rest_route('secure/v1', '/profile', [

        'methods' => 'POST',

        'callback' => function ($request) {

            $name = sanitize_text_field(
                $request->get_param('name')
            );

            return rest_ensure_response([
                'success' => true,
                'name' => $name
            ]);
        },

        'permission_callback' => function () {

            return current_user_can('edit_posts');
        },

        'args' => [
            'name' => [
                'required' => true,
                'sanitize_callback' => 'sanitize_text_field',
                'validate_callback' => function ($value) {
                    return is_string($value)
                        && strlen($value) <= 100;
                }
            ]
        ]

    ]);

});

The remediated version includes:

  • An explicit permission callback.
  • Capability-based authorization.
  • Input sanitization.
  • Input validation.
  • A structured REST API response.

For cookie-authenticated REST API requests, WordPress also supports the X-WP-Nonce header using a nonce generated for the wp_rest action.

5. Practical Security Testing Using CLI Tools

Writing secure code is only one part of application security. Developers should also test their implementations before deploying them.

The following commands can be used in an authorized local WordPress Docker lab.

Check the WordPress REST API:

curl -i http://localhost/wp-json/

Inspect the custom endpoint:

curl -i -X POST \
  http://localhost/wp-json/secure/v1/profile \
  -H "Content-Type: application/json" \
  -d '{"name":"Security Test"}'

An unauthenticated request should be rejected when the endpoint requires an authorized user.

Check installed WordPress plugins:

wp plugin list

Check WordPress core version:

wp core version

Run WordPress coding standards checks:

composer require --dev \
  wp-coding-standards/wpcs
vendor/bin/phpcs \
  --standard=WordPress \
  wp-content/plugins/my-security-plugin/

Check PHP syntax:

find wp-content/plugins/my-security-plugin \
  -name "*.php" -exec php -l {} \;

These commands help identify coding-standard violations and PHP syntax errors. They do not independently prove that an application is secure.

A useful security testing checklist includes:

  • Check authorization on every sensitive endpoint.
  • Verify nonce handling for state-changing browser requests.
  • Use prepared SQL statements.
  • Sanitize and validate incoming data.
  • Escape output according to its context.
  • Review plugin dependencies and known vulnerabilities.
  • Test unauthorized and invalid requests in a controlled environment.

Get started with secure WordPress development:

Download Secure WordPress Plugin Boilerplate: https://hackmywebsite.io/?utm_source=med&utm_campaign=wp_internals

Hack My Website provides security-focused resources for developers working to identify and address web application vulnerabilities.

Conclusion

WordPress security depends on understanding how its internal components work together.

Hooks provide flexibility, nonces help protect against CSRF, filters allow controlled data modification, and capability checks ensure that users can only perform authorized actions.

Prepared database queries, proper input handling and context-aware output escaping help prevent common vulnerabilities such as SQL Injection and XSS.

Building secure WordPress themes and plugins is not about adding security checks at the end. It is about making security part of the development process from the beginning.

📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.