Make WordPress Core

Opened 21 months ago

Last modified 17 months ago

#48360 new defect (bug)

`meta_value` is ignored when empty string is provided

Reported by: JPry Owned by:
Milestone: Awaiting Review Priority: normal
Severity: normal Version: 3.2
Component: Query Keywords:
Focuses: Cc:

Description (last modified by davidbaumwald)

When trying to create a custom query using meta_* parameters, WP_Meta_Query will ignore meta_value if it is an empty string.

This does appear to be somewhat intentional, since WP_Query will set the default value for meta_value to an empty string. This can be seen here: https://core.trac.wordpress.org/browser/trunk/src/wp-includes/class-wp-meta-query.php#L255

The problem comes when you want to write a query that specifically targets meta keys that have empty values. The 'meta_value' => '' parameter is stripped, and then the query does not behave properly. Here's an example query:

$args = array(
    'post_type'      => 'product',
    'posts_per_page' => 10,
    'meta_key'       => '_regular_price',
    'meta_value'     => '',
    'meta_compare'   => '=',

$query = new WP_Query( $args );

I would like to propose that an empty string be allowed for meta_value. Alternatively, the fact that an empty value will be stripped should at least be documented more clearly so that developers know to expect that behavior.

Props also to @richardbuff for helping identify the issue.

Change History (4)

This ticket was mentioned in Slack in #cli by jpry. View the logs.

21 months ago

#2 @davidbaumwald
21 months ago

  • Description modified (diff)

#3 @nofearinc
20 months ago

I'd love to get this sorted (since I've dealt with this before) but here's what the meta query class states right now:

		// WP_Query sets 'meta_value' = '' by default.
		if ( isset( $qv['meta_value'] ) && '' !== $qv['meta_value'] && ( ! is_array( $qv['meta_value'] ) || $qv['meta_value'] ) ) {
			$primary_meta_query['value'] = $qv['meta_value'];

I can relate with the use case and we can update the default behavior for meta queries, and probably patch it in WP_Query so it passes null as a default value. However, I'm not sure how robust this would be, especially with third-party plugins relying on this core behavior.

This ticket was mentioned in Slack in #cli by schlessera. View the logs.

17 months ago

Note: See TracTickets for help on using tickets.