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?

1
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

Leave a Reply

Your email address will not be published. Required fields are marked *