sanitize_sql_orderby() WordPress Function

The sanitize_sql_orderby() function is a utility function that allows you to safely generate a SQL ORDER BY clause. This function takes a column name and a list of possible order directions (ascending or descending) as its parameters. It then sanitizes the column name and generates a safe SQL ORDER BY clause that can be used in a SQL query.

sanitize_sql_orderby( string $orderby ) #

Ensures a string is a valid SQL ‘order by’ clause.


Description

Accepts one or more columns, with or without a sort order (ASC / DESC). e.g. ‘column_1’, ‘column_1, column_2’, ‘column_1 ASC, column_2 DESC’ etc.

Also accepts ‘RAND()’.


Top ↑

Parameters

$orderby

(string)(Required)Order by clause to be validated.


Top ↑

Return

(string|false) Returns $orderby if valid, false otherwise.


Top ↑

Source

File: wp-includes/formatting.php

function sanitize_sql_orderby( $orderby ) {
	if ( preg_match( '/^\s*(([a-z0-9_]+|`[a-z0-9_]+`)(\s+(ASC|DESC))?\s*(,\s*(?=[a-z0-9_`])|$))+$/i', $orderby ) || preg_match( '/^\s*RAND\(\s*\)\s*$/i', $orderby ) ) {
		return $orderby;
	}
	return false;
}

Top ↑

Changelog

Changelog
VersionDescription
2.5.1Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.

Show More