1

I have some posts on my WordPress site, and let's say I want to add a random number for each post with $num as key and random() as value. Then I want to access them with something like:

$post->num or post_num()

Can this be done during The Loop? Since the value will change every time it is executed, I need to make it during The Loop. I can't add this random number as a custom field.

Is there a way to achieve this?

1

Yep, it's not very common, but perfectly viable and nifty technique.

After the posts are retrieved in WP_Query they are passed through the_posts filter like this (where $this is WP_Query instance):

$this->posts = apply_filters_ref_array( 'the_posts', array( $this->posts, &$this ) );

You just loop through array and assign the extra data you need to objects. Don't forget to check the query for being right query you want to target.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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