Forest
Forest

Reputation: 55

Wordpress output to array in query from custom field

I have created a custom field named "sec1array" in my categories so that i can add an array, for example 1,2,3,4

I want to retrieve that array and output it in the loop, so I created this code.

$seconearray = array($cat_data['sec1array']);

$args = array( 
'post__in' => $seconearray
);

However, it only seems to be outputting the first post in the array. Is it something to do with the way the comma is outputting?

If I print $seconearray it outputs correctly, example 1,2,3,4

Upvotes: 0

Views: 41

Answers (1)

R. Chappell
R. Chappell

Reputation: 1282

What you are doing is storing a string value of "1,2,3,4" in your database which when you are trying to construct an array from it like array("1,2,3,4") you end up just assigning a single value to that new array. This is why it only contains a single value.

You need to store your value in a serializable format so it can be converted back to an array after you save it to the database. There are many ways to do this, I'm sure others will give more examples:

JSON encode it

json_encode(array(1,2,3,4)); // store this in your db
json_decode($cat_data['sec1array']); // outputs an array

Or, you can use PHP serialize

serialize(array(1,2,3,4)); // store this in your db
unserialize($cat_data['sec1array']); // outputs an array

If you want to keep your string, you can explode it:

explode(',', $cat_data['sec1array']); // outputs your array of 1,2,3,4.

Using any of these methods will work. Finally you'll end up with an example like:

$seconearray = explode(',', $cat_data['sec1array']);
$args = array( 
    'post__in' => $seconearray
);

Upvotes: 2

Related Questions