0

I set up a meta field related_topics that I use to associate lesson topics to a custom post type lesson.

I read here

https://stackoverflow.com/questions/19640850/wordpress-how-to-return-meta-with-query-posts

that you can access meta fields directly from a post object in the manner $post->my_field.

For a given lesson there could be several related topics. For a given lesson that has multiple topics, I noticed that $post->related_topics only returns the first topic instance, when in fact there are more than one. Is there some method to use, something like $post->related_topics->all()? Maybe with this convention only one item is returned by default even if there is a collection?

thanks, Brian

3
  • $post->related_topics is not a standard field on the WP_Post object (the post object only contains the data from the wp_posts table). Are you adding this? Commented Oct 31, 2019 at 14:52
  • When you have custom fields as meta data where the field has an id of the post you can get the data in the way I mention. Just learned about it yesterday. See here: stackoverflow.com/questions/19640850/… In my case, I have a related_topics meta field and for the post in question there are 4 related topics. But $post->related_topics is only returning one item.
    – Brian
    Commented Oct 31, 2019 at 17:04
  • The post object is only going to return what you put into it. You're using get_post_meta() to get the data you're putting into it, so that's really what you should be asking about. Commented Oct 31, 2019 at 23:51

1 Answer 1

0

By calling $post->related_topics you are using the magic functions of the object ( __get and __isset )

To make it simple, behind the scenes it is the same as :

get_post_meta( $post->ID, 'related_topics', true );

So you are just abstracting the use of the function get_post_meta. And as you can see, the third argument is defined as TRUE. And this tells the function to return a single value.

So its ok if your meta is a single value, but if you have multiple values, then you must set the third argument as false. Thus you shouldn't use the magic functions, but rather call get_post_meta yourself.

So, just use :

$topics = get_post_meta( $post->ID, 'related_topics', false);

like that you have an array of values

1
  • Ok, I was hoping to just access all my data using $post->some_other_data sort of syntax but I guess I will just use the meta function. thanks, Brian
    – Brian
    Commented Nov 1, 2019 at 6:21

Your Answer

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

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