WP_Date_Query::validate_column( string $column ): string

Validates a column name parameter.

Description

Column names without a table prefix (like ‘post_date’) are checked against a list of allowed and known tables, and then, if found, have a table prefix (such as ‘wp_posts.’) prepended. Prefixed column names (such as ‘wp_posts.post_date’) bypass this allowed check, and are only sanitized to remove illegal characters.

Parameters

$columnstringrequired
The user-supplied column name.

Return

string A validated column name value.

Source

public function validate_column( $column ) {
	global $wpdb;

	$valid_columns = array(
		'post_date',
		'post_date_gmt',
		'post_modified',
		'post_modified_gmt',
		'comment_date',
		'comment_date_gmt',
		'user_registered',
		'registered',
		'last_updated',
	);

	// Attempt to detect a table prefix.
	if ( ! str_contains( $column, '.' ) ) {
		/**
		 * Filters the list of valid date query columns.
		 *
		 * @since 3.7.0
		 * @since 4.1.0 Added 'user_registered' to the default recognized columns.
		 * @since 4.6.0 Added 'registered' and 'last_updated' to the default recognized columns.
		 *
		 * @param string[] $valid_columns An array of valid date query columns. Defaults
		 *                                are 'post_date', 'post_date_gmt', 'post_modified',
		 *                                'post_modified_gmt', 'comment_date', 'comment_date_gmt',
		 *                                'user_registered', 'registered', 'last_updated'.
		 */
		if ( ! in_array( $column, apply_filters( 'date_query_valid_columns', $valid_columns ), true ) ) {
			$column = 'post_date';
		}

		$known_columns = array(
			$wpdb->posts    => array(
				'post_date',
				'post_date_gmt',
				'post_modified',
				'post_modified_gmt',
			),
			$wpdb->comments => array(
				'comment_date',
				'comment_date_gmt',
			),
			$wpdb->users    => array(
				'user_registered',
			),
			$wpdb->blogs    => array(
				'registered',
				'last_updated',
			),
		);

		// If it's a known column name, add the appropriate table prefix.
		foreach ( $known_columns as $table_name => $table_columns ) {
			if ( in_array( $column, $table_columns, true ) ) {
				$column = $table_name . '.' . $column;
				break;
			}
		}
	}

	// Remove unsafe characters.
	return preg_replace( '/[^a-zA-Z0-9_$\.]/', '', $column );
}

Hooks

apply_filters( ‘date_query_valid_columns’, string[] $valid_columns )

Filters the list of valid date query columns.

Changelog

VersionDescription
3.7.0Introduced.

User Contributed Notes

You must log in before being able to contribute a note or feedback.