While learning about metadata lazy-loading, I met these lines of code:

// Don't use `wp_list_pluck()` to avoid by-reference manipulation.
$comment_ids = array();
if ( is_array( $comments ) ) {
    foreach ( $comments as $comment ) {
        if ( $comment instanceof WP_Comment ) {
            $comment_ids[] = $comment->comment_ID;

I thought it relates to this topic but there're no references here and the only foreach loop is wrapped inside a function, how by-reference manipulation can happen in this case?

And, for best practice, when should we use wp_list_pluck() function?

  • I'm with you, fwiw. I've looked at the function source, codex & dev docs and can't see what that comment refers to. Jun 10, 2016 at 21:17

1 Answer 1


In any foreach loop, the last value of the array being looped over remains after the end of the foreach loop. That is why one should actually always unset that value after the foreach loop is done.

wp_list_pluck() is also just a basic foreach loop if $index_key is not passed. Also, as with any foreach loop, the last value of the array remains after the end of the foreach loop, and I think this is what that line refers to in the codex.

However, that assumption is wrong. Functions are self contained pieces of code, and except for globals, these pieces of code inside a function are only avaiable to the function itself. wp_list_pluck() does not globalize any of its intenal values (variables), so even if the last value of the array is still available after the foreach loop inside the function, and does not get unset, it is not available to any piece of code outside the function, so you cannot have the pass-by-reference issue as described in that line in the codex.

wp_list_pluck() is as valid to use as any simple foreach loop. The choice is up to you. I personally prefer wp_list_pluck() as it saves on code, and you do not need to remember to unset variables which can later lead to debugging nightmare.

Just a final note, wp_list_pluck() can also replace array_column as it works the same if $index_key is passed to the function

  • Unset or reset?
    – fuxia
    Jun 6, 2016 at 12:56
  • @toscho AFAIK and from what I have learned, unset( $value ) after a foreach loop, wp_reset_postdata() if you used setup_postdata( $post ) in a foreach loop, and reset() sets the internal pointer back to the first item in an array. If I'm wrong, or if you have anything else or different to add, you should do that in an answer so that we all benefit from that. IMHO, this is a question that most of the community can benefit from, and if I'm wrong, correct me then and post a proper answer Jun 6, 2016 at 13:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.