Sample alert How it works Coverage PENTEST METHODOLOGY DOCS PRICING FAQ MCP CONTACT LOG IN SCAN MY APP →

AI-written WordPress plugin: security holes to fix

FIX / VIBE-CODED WP PLUGIN / 9 MIN READ

An AI-written WordPress plugin often has request handlers that skip the nonce check and the capability check. They also often put user input straight into SQL. Search for every handler and add the three checks. Test each one as a visitor and as a subscriber. The plugin can work in your test and still be open to the internet.

This guide shows what to search for, how to fix each handler with correct PHP, and how to test the result.

Why do AI-written plugins have these holes?

The AI tool writes code that makes the feature work. It does not know who must be allowed to call the feature. A WordPress plugin has many entry points, and each entry point needs its own check.

The WordPress Plugin Handbook has a security chapter that lists the checks. The AI tool often writes only the first half of the job. It reads the input and does the action. It skips the checks before and after.

These are the usual faults:

  • A missing nonce. The handler does not call check_ajax_referer() or wp_verify_nonce(). A page on another site can make a logged-in admin send the request.
  • A missing capability check. The handler does not call current_user_can(). Any logged-in user, or any visitor, can call it.
  • An open hook. The plugin uses wp_ajax_nopriv_ for an action that changes data.
  • An open REST route. The route uses 'permission_callback' => '__return_true' for private data.
  • Raw SQL. The plugin joins $_POST values into a query string.
  • No output escaping. The plugin prints stored values without esc_html(), so a user can store a script.
  • An unsafe upload. The plugin saves any file type into wp-content/uploads.
  • A direct file call. A PHP file runs when a visitor opens its address, because it has no ABSPATH check.

Caution: A plugin that you wrote with an AI tool runs with full access to your database and your files. A single open handler can give an attacker control of the site.

How do I find the open handlers?

Search the plugin code. Use the shell in the plugin folder. Each search finds one kind of entry point.

  1. Find AJAX handlers that a visitor can call.
grep -rn "wp_ajax_nopriv_" wp-content/plugins/your-plugin
  1. Find all AJAX handlers. Compare the list with the first list.
grep -rn "wp_ajax_" wp-content/plugins/your-plugin
  1. Find REST routes and read each permission_callback.
grep -rn -A8 "register_rest_route" wp-content/plugins/your-plugin
grep -rn "__return_true" wp-content/plugins/your-plugin

A route with no permission_callback at all is also a fault. Current WordPress shows a notice for it.

  1. Find queries that do not use prepare.
grep -rnE '\$wpdb->(query|get_results|get_var|get_row|get_col)\(' wp-content/plugins/your-plugin | grep -v prepare
  1. Find all places that read user input.
grep -rnE '\$_(GET|POST|REQUEST|FILES|COOKIE)' wp-content/plugins/your-plugin
  1. Find the other entry points: shortcodes, admin_post_ hooks, and init or admin_init hooks that read $_GET or $_POST.
grep -rnE "add_shortcode|admin_post_|add_action\( *'(admin_)?init'" wp-content/plugins/your-plugin

Write each result in a list. Mark each entry point with three answers: who can call it, what it changes, and which check protects it.

You can also run the official Plugin Check plugin on a test site. It reports many of these faults. You can add the WordPress Coding Standards for PHP_CodeSniffer. They flag unescaped output, missing nonce checks and unprepared queries. A tool finds only some faults. Do the manual read too.

How do I fix an AJAX handler?

Every AJAX handler needs three things in this order: a nonce check, a capability check, and clean input.

This is a typical unsafe handler from an AI tool:

// Unsafe. Do not use.
add_action( 'wp_ajax_nopriv_myplugin_delete_item', 'myplugin_delete_item' );
add_action( 'wp_ajax_myplugin_delete_item', 'myplugin_delete_item' );

function myplugin_delete_item() {
	global $wpdb;
	$id = $_POST['id'];
	$wpdb->query( "DELETE FROM {$wpdb->prefix}myplugin_items WHERE id = $id" );
	echo 'ok';
	wp_die();
}

A visitor can call this handler. The query has no placeholder, so the id value can contain SQL. The handler has no nonce and no capability check.

This is the fixed handler:

add_action( 'wp_ajax_myplugin_delete_item', 'myplugin_delete_item' );

function myplugin_delete_item() {
	check_ajax_referer( 'myplugin_delete_item', 'nonce' );

	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( array( 'message' => 'Forbidden' ), 403 );
	}

	$id = isset( $_POST['id'] ) ? absint( wp_unslash( $_POST['id'] ) ) : 0;
	if ( 0 === $id ) {
		wp_send_json_error( array( 'message' => 'Invalid id' ), 400 );
	}

	global $wpdb;
	$deleted = $wpdb->delete(
		$wpdb->prefix . 'myplugin_items',
		array( 'id' => $id ),
		array( '%d' )
	);

	if ( false === $deleted ) {
		wp_send_json_error( array( 'message' => 'Database error' ), 500 );
	}

	wp_send_json_success();
}

Note these points:

  • The code removes wp_ajax_nopriv_. Only logged-in users reach the handler.
  • check_ajax_referer() stops the request with a 403 response when the nonce is wrong. The second argument is the name of the field in $_POST.
  • current_user_can() checks the right of the user. Use the smallest capability that fits the action. Use manage_options for settings, edit_post with a post ID for a single post, and delete_users for users.
  • absint() turns the value into a positive integer.
  • $wpdb->delete() with a format array uses placeholders for you.

The page must create the nonce and send it. Create it in PHP, and pass it to the script:

add_action( 'admin_enqueue_scripts', 'myplugin_enqueue' );

function myplugin_enqueue( $hook ) {
	wp_enqueue_script( 'myplugin-admin', plugins_url( 'admin.js', __FILE__ ), array(), '1.0.0', true );
	wp_localize_script(
		'myplugin-admin',
		'mypluginData',
		array(
			'ajaxUrl' => admin_url( 'admin-ajax.php' ),
			'nonce'   => wp_create_nonce( 'myplugin_delete_item' ),
		)
	);
}

The script then sends action, nonce and id in the POST body.

Warning: Do not treat the nonce as a login. A nonce is a token that ties a request to a user session and a time window. Any user who can load the page gets a valid nonce. The capability check is what controls access.

What if the action must be public?

Some actions must work for visitors, for example a contact form. Use wp_ajax_nopriv_ only for these. Then follow these rules:

  1. The action must not change settings, users, files or other users’ data.
  2. Validate and sanitize every field.
  3. Limit the number of requests, for example with a CAPTCHA or a transient counter per IP address.
  4. Do not return data that belongs to other users.

A nonce on a public page can be cached by a page cache. Then the nonce becomes old and valid requests fail. Test the form with the cache on.

How do I fix a REST route?

Every REST route needs a permission_callback. The callback decides who can call the route. The REST API handbook states that you must set it for every route.

This is a typical unsafe route:

// Unsafe. Do not use.
register_rest_route( 'myplugin/v1', '/orders', array(
	'methods'             => 'GET',
	'callback'            => 'myplugin_get_orders',
	'permission_callback' => '__return_true',
) );

This is the fixed route:

add_action( 'rest_api_init', 'myplugin_register_routes' );

function myplugin_register_routes() {
	register_rest_route(
		'myplugin/v1',
		'/orders/(?P<id>\d+)',
		array(
			'methods'             => WP_REST_Server::READABLE,
			'callback'            => 'myplugin_get_order',
			'permission_callback' => 'myplugin_can_read_orders',
			'args'                => array(
				'id' => array(
					'validate_callback' => function ( $value ) {
						return is_numeric( $value );
					},
					'sanitize_callback' => 'absint',
				),
			),
		)
	);
}

function myplugin_can_read_orders() {
	return current_user_can( 'manage_options' );
}

function myplugin_get_order( WP_REST_Request $request ) {
	global $wpdb;
	$row = $wpdb->get_row(
		$wpdb->prepare(
			"SELECT id, status, total FROM {$wpdb->prefix}myplugin_orders WHERE id = %d",
			$request['id']
		),
		ARRAY_A
	);

	if ( null === $row ) {
		return new WP_Error( 'myplugin_not_found', 'Order not found', array( 'status' => 404 ) );
	}

	return rest_ensure_response( $row );
}

Use __return_true only when the data is public on purpose. A list of published product names is one example.

For a route that edits one object, check the object, not only the role. Use current_user_can( 'edit_post', $post_id ) or compare the owner ID with get_current_user_id(). A role check alone lets one user change the data of another user. The admin page guide explains the same rule for admin areas.

The REST API checks a nonce for you when the request uses the login cookie. The JavaScript sends it in the X-WP-Nonce header, and the value comes from wp_create_nonce( 'wp_rest' ). Without that nonce, WordPress treats the request as a visitor request. This is why the permission_callback must be correct for the visitor case.

How do I fix the database queries?

Use $wpdb->prepare() for every query that contains a variable. Use %d for integers, %f for floats and %s for strings. The wpdb::prepare reference lists the rules.

// Unsafe. Do not use.
$rows = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}myplugin_items WHERE name = '" . $_GET['name'] . "'" );
$name = isset( $_GET['name'] ) ? sanitize_text_field( wp_unslash( $_GET['name'] ) ) : '';

$rows = $wpdb->get_results(
	$wpdb->prepare(
		"SELECT id, name FROM {$wpdb->prefix}myplugin_items WHERE name = %s",
		$name
	)
);

For a LIKE search, escape the wildcard characters:

$term = $wpdb->esc_like( $name );
$rows = $wpdb->get_results(
	$wpdb->prepare(
		"SELECT id, name FROM {$wpdb->prefix}myplugin_items WHERE name LIKE %s",
		'%' . $term . '%'
	)
);

For an IN list, build one placeholder for each value:

$ids          = array_map( 'absint', $ids );
$placeholders = implode( ',', array_fill( 0, count( $ids ), '%d' ) );
$rows         = $wpdb->get_results(
	$wpdb->prepare(
		"SELECT id, name FROM {$wpdb->prefix}myplugin_items WHERE id IN ($placeholders)",
		$ids
	)
);

A placeholder works only for values. It does not work for a column name or for ORDER BY. Check these against a fixed list:

$allowed = array( 'name', 'created_at' );
$orderby = isset( $_GET['orderby'] ) ? sanitize_key( wp_unslash( $_GET['orderby'] ) ) : 'name';
if ( ! in_array( $orderby, $allowed, true ) ) {
	$orderby = 'name';
}

Where you can, use WP_Query, get_posts() or the $wpdb->insert(), update() and delete() methods. They prepare the values for you. The SQL injection guide shows more patterns and tests.

How do I fix output, uploads and direct file access?

Escape every output

Sanitize on input. Escape on output. Use the function that matches the place where the value goes.

echo '<h2>' . esc_html( $title ) . '</h2>';
echo '<input type="text" value="' . esc_attr( $value ) . '">';
echo '<a href="' . esc_url( $link ) . '">Open</a>';
echo wp_kses_post( $description );

The data validation chapter of the handbook lists the sanitize and escape functions.

Check uploads

Use wp_handle_upload() with a list of allowed types. Check the capability first.

function myplugin_handle_upload() {
	check_ajax_referer( 'myplugin_upload', 'nonce' );

	if ( ! current_user_can( 'upload_files' ) ) {
		wp_send_json_error( array( 'message' => 'Forbidden' ), 403 );
	}

	if ( empty( $_FILES['file'] ) ) {
		wp_send_json_error( array( 'message' => 'No file' ), 400 );
	}

	require_once ABSPATH . 'wp-admin/includes/file.php';

	$result = wp_handle_upload(
		$_FILES['file'], // phpcs:ignore WordPress.Security.ValidatedSanitizedInput
		array(
			'test_form' => false,
			'mimes'     => array(
				'jpg|jpeg' => 'image/jpeg',
				'png'      => 'image/png',
				'pdf'      => 'application/pdf',
			),
		)
	);

	if ( isset( $result['error'] ) ) {
		wp_send_json_error( array( 'message' => $result['error'] ), 400 );
	}

	wp_send_json_success( array( 'url' => esc_url_raw( $result['url'] ) ) );
}

Never allow php, phtml, phar or svg uploads from untrusted users. Read the file upload guide for more tests.

Block direct file calls

Add this line at the top of every PHP file that is not an entry point:

defined( 'ABSPATH' ) || exit;

Without it, a visitor can open /wp-content/plugins/your-plugin/includes/helper.php and run the file outside WordPress. The result can be a path leak or a code run.

How do I test the fix?

Test each entry point with three kinds of caller: a visitor, a subscriber, and an admin. The visitor and the subscriber must get a refusal.

  1. Create a subscriber on a test site.
wp user create tester tester@example.com --role=subscriber --user_pass='use-a-long-test-password'
  1. Call each AJAX action with no login. Expect a 403 status or a 0 or -1 body.
curl -i -X POST https://your-site.example/wp-admin/admin-ajax.php \
  -d "action=myplugin_delete_item" -d "id=1"
  1. Call each REST route with no login. Expect 401 or 403.
curl -i https://your-site.example/wp-json/myplugin/v1/orders/1
  1. Create an application password for the subscriber in the profile screen. Call the route with it. Expect 403.
curl -i -u "tester:APPLICATION_PASSWORD" https://your-site.example/wp-json/myplugin/v1/orders/1
  1. Send a request with a wrong or missing nonce, with a valid admin login. Expect a refusal.
  2. Send a quote character in each text field, and a very long value. Expect no database error in the response.
  3. Open the address of each PHP file in the plugin folder. Expect a blank page or a 403 status, not an error message with a path.

Warning: Run these tests on a copy of the site. A test that works also changes the data.

Fix every request that returns data or a success message. Then run the test again.

How do I stop this in the future?

  1. Put the rules in the prompt. Write: “Every handler must call check_ajax_referer and current_user_can. Every query must use $wpdb->prepare. Every route must have a permission_callback.”
  2. Run Plugin Check and PHPCS with the WordPress standard in each build.
  3. Read each diff for nopriv, __return_true and any query without prepare.
  4. Keep a list of entry points. Add each new handler to the list with its check.
  5. Install plugins only from a source that you trust. Remove plugins that you do not use. An unused plugin still has open files.
  6. Scan the live site from outside after each release. A scan sees the handlers that a visitor can reach. See the login attack guide for the next layer of protection.

When should I get help?

Get help in these cases:

  • The plugin handles payments, orders or personal data, and you did not review the checks.
  • The logs show calls to admin-ajax.php or /wp-json/ with SQL characters in the values.
  • You find a new admin user, a new PHP file in wp-content/uploads, or a changed core file.
  • You cannot tell which handlers are public.

If you find signs of a break-in, take the site offline, restore a clean backup, and change all passwords and keys. Then ask a security engineer to review the plugin.

Common questions

Is a nonce enough to protect an AJAX handler?
No. A nonce proves that the request came from a page that your site made. It does not prove that the user has the right to do the action. Use a capability check too.
Can I use wp_ajax_nopriv_ for a public form?
Yes, but only for actions that a visitor can safely do. Validate all input. Never use it for actions that change settings, users or files.
Is __return_true in permission_callback always wrong?
No. It is correct for data that is public on purpose. It is wrong for any route that reads private data or changes data.
Does $wpdb->prepare stop all SQL injection?
It stops injection in values. It does not protect table names, column names or an ORDER BY value. Check those values against a fixed list.
How do I test the plugin as a user with a low role?
Create a subscriber account. Send each request with that account and expect a 403 status. Then send it with no login and expect the same.

Test your wordpress endpoints

A VibeEval scan calls the AJAX and REST endpoints of your live WordPress site without a login and reports the ones that return data or accept changes.

14-day free trial · Cancel anytime

SCAN YOUR APP →