Make WordPress Core

Opened 2 years ago

Last modified 2 years ago

#56262 new enhancement

WP_List_Util::pluck doesn't support a null $field

Reported by: iandunn's profile iandunn Owned by:
Milestone: Awaiting Review Priority: low
Severity: minor Version: 3.1
Component: General Keywords: has-patch needs-testing
Focuses: Cc:

Description

array_column() accepts a null value for the $column_key parameter. When passed null, it returns the complete array, which is a useful trick for reindexing database results, etc.

$array = [
    [ 'id' => 123, 'name' => 'Joe' ],
    [ 'id' => 345, 'name' => 'Sally' ]
];

array_column( $array, null, 'id' ); // [ 123 => [ 'id' => 123, 'name' => 'Joe'] ...

wp_list_pluck() doesn't work when using that on an object, though:

Warning: Undefined property: stdClass::$ in wp-includes/class-wp-list-util.php on line 185

It seems like array_column() has had support for objects since PHP7, so one way to achieve this might be something like:

if ( version_compare( ... ) {
    return array_column( $this->output, $field, $index_key )
}

// existing code remains as fallback for older versions

It might be good to use something like 7.0.7 to skip a few bugs that were fixed.

Attachments (1)

56262.diff (1.3 KB) - added by azouamauriac 2 years ago.

Download all attachments as: .zip

Change History (4)

#1 @iandunn
2 years ago

  • Priority changed from normal to low
  • Severity changed from normal to minor

@azouamauriac
2 years ago

#2 @azouamauriac
2 years ago

  • Keywords has-patch needs-testing added

#3 @iandunn
2 years ago

56262.diff looks like a good start!

Two helpful improvements could be adding unit tests and inline docs (adding a @since, updating the $field parameter description, etc).

is_null( $field ) might be more explicit / self documenting than isset(), especially after the $field docs are updated to mention that null can be passed.

Using isset() could also unintentionally hide PHP warnings (and therefore bugs) when devs make a typo in the field name, etc.

Note: See TracTickets for help on using tickets.