Jose Carrillo
Jose Carrillo

Reputation: 1860

Wordpress Multiple post from a post ID

I have a usermeta set up for my users that saves favorite post to their profile. I am getting this usemeta(which keeps the post IDs in it). Once I get it, I have it in an one dimensional array. I want to display a list of their favorite posts. I have tried this:

$favorites //array of favorites, that has come from the databese 

$query = new WP_Query( array( 'post__in' => array( 2, 5, 12, 14, 20 ) ) );

and it would work fine, if I hard coded the post IDs , but since it is an array I can't just pass in array such, it returns nothing.

$query = new WP_Query( array( 'post__in' => $favorites) );

it does not accept it, I also tried to implode the array in to a string as such:

$fav_list = implode("," , $favorites);

and i get this, which is exactly what I need as a string "124,126,125,130,132,140,142", without the quotes. I would then use it as such:

$query = new WP_Query( array( 'post__in' => array($fav_list) ) );

But again it doesn't work, it returns nothing. Since the favorites list is being pulled from the usermeta and the user can change it, I can't hard code the list.

Can anyone help me? Is it even possible with WP_Query. Not sure why it is not taking the string or what I am doing wrong. I red through the Wordpress Documentation but haven't found a solution.

Thanks in advance.

Upvotes: 0

Views: 109

Answers (1)

Nick Pickering
Nick Pickering

Reputation: 3185

Arrays don't get stored in the database as arrays. They get serialized. When you pull the array from the database you have to unserialize() it.

http://php.net/manual/en/function.unserialize.php

If you var_dump($favorites) right after it comes out of the database, you'll notice it's a weird-lookin' string and not an array. var_dump(unserialize($favorites)) will show you your original array.

Upvotes: 1

Related Questions