WP_Date_Query::validate_column( string $column )

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

$column

(string) (Required) The user-supplied column name.

Return

(string) A validated column name value.

Source

File: wp-includes/class-wp-date-query.php

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 ( false === strpos( $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.
			 *
			 * @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'
			 */
			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 );
	}

Changelog

Version Description
3.7.0 Introduced.

© 2003–2021 WordPress Foundation
Licensed under the GNU GPLv2+ License.
https://developer.wordpress.org/reference/classes/wp_date_query/validate_column