WP_List_Util::pluck( int|string $field, int|string $index_key = null ): array

Plucks a certain field out of each element in the input array.

Description

This has the same functionality and prototype of array_column() (PHP 5.5) but also supports objects.

Parameters

$fieldint|stringrequired
Field to fetch from the object or array.
$index_keyint|stringoptional
Field from the element to use as keys for the new array.

Default:null

Return

array Array of found values. If $index_key is set, an array of found values with keys corresponding to $index_key. If $index_key is null, array keys from the original $list will be preserved in the results.

Source

public function pluck( $field, $index_key = null ) {
	$newlist = array();

	if ( ! $index_key ) {
		/*
		 * This is simple. Could at some point wrap array_column()
		 * if we knew we had an array of arrays.
		 */
		foreach ( $this->output as $key => $value ) {
			if ( is_object( $value ) ) {
				$newlist[ $key ] = $value->$field;
			} elseif ( is_array( $value ) ) {
				$newlist[ $key ] = $value[ $field ];
			} else {
				_doing_it_wrong(
					__METHOD__,
					__( 'Values for the input array must be either objects or arrays.' ),
					'6.2.0'
				);
			}
		}

		$this->output = $newlist;

		return $this->output;
	}

	/*
	 * When index_key is not set for a particular item, push the value
	 * to the end of the stack. This is how array_column() behaves.
	 */
	foreach ( $this->output as $value ) {
		if ( is_object( $value ) ) {
			if ( isset( $value->$index_key ) ) {
				$newlist[ $value->$index_key ] = $value->$field;
			} else {
				$newlist[] = $value->$field;
			}
		} elseif ( is_array( $value ) ) {
			if ( isset( $value[ $index_key ] ) ) {
				$newlist[ $value[ $index_key ] ] = $value[ $field ];
			} else {
				$newlist[] = $value[ $field ];
			}
		} else {
			_doing_it_wrong(
				__METHOD__,
				__( 'Values for the input array must be either objects or arrays.' ),
				'6.2.0'
			);
		}
	}

	$this->output = $newlist;

	return $this->output;
}

Changelog

VersionDescription
4.7.0Introduced.

User Contributed Notes

  1. Skip to note 2 content

    It looks like this error is relatively common on the Add Plugins page:
    stdClass::$plugin in .../htdocs/wp-includes/class-wp-list-util.php on line 153

    I quieted the error on my site by adding if(!empty($value->$field)) checks before calling the field. I have no idea if this is best solution, but at least it fails quietly now.

    foreach ( $this->output as $key => $value ) {
    				if ( is_object( $value ) ) {
    					if(!empty($value->$field)) $newlist[ $key ] = $value->$field;
    				} else {
    					if(!empty($value[ $field ])) $newlist[ $key ] = $value[ $field ];
    				}
    			}

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