0

so I am trying to use a foreach to pull content from a custom field in multiple posts, but it just wont work. I can get it to work for a simple textarea string but I am struggling getting it to work for arrays. This is the working code for a string:

$posts = get_posts(array(
'numberposts' => -1,
'post_type' => 'post',));
foreach($posts as $post)
{
$string = get_post_meta($post->ID, 'simple_string', true);
echo $string;
}

And elsewhere in the site this code works for getting into a specific posts custom field array:

$arr = get_field('array');
$arr2 = $arr[0]['string'];
$string = implode(", ",$arr2);
echo $string;

Why doesn't this work?

$posts = get_posts(array(
'numberposts' => -1,
'post_type' => 'post',));
foreach($posts as $post)
{
$arr = get_post_meta($post->ID, 'array', true);
$arr2 = $arr[0]['string'];
$string = implode(", ",$arr2);
echo $string;
}

Thanks in advance for taking a look.

  • When saved, the post-meta would need to be a string, so you'll need to implode/serialize the array and save to the db as string, then explode/unserialize it after you withdraw the string from the db. – admcfajn Aug 30 '18 at 16:12
0

The custom fields I am using are from the plugin ACF (Advanced Custom Fields).

I finally looked at the ACF website, which I should have done originally, and found the function get_field can specify a post so here is the working code:

$posts = get_posts(array(
'numberposts' => -1,
'post_type' => 'post',));
foreach($posts as $post)
{
$arr = get_field('array', $post->ID);
$arr2 = $arr[0]['string'];
$string = implode(", ",$arr2);
echo $string;
}
0

Yep, get_field() makes it easier, but get_post_meta() is almost always more performant because get_field() uses more database queries.

If I remember right, it works like this:

$posts = get_posts(
    array(
        'numberposts' => -1,
        'post_type' => 'post',
    )
);
foreach($posts as $post) {
    $serialized_string = get_post_meta( $post->ID, 'array', true );
    $arr = unserialize( $serialized_string ); // unserialize it here
    $arr2 = $arr[0]['string']; // assuming this is a valid index
    $string = implode( ", ", $arr2 );
    echo $string;
}

If it doesn't work please do a var_dump() of $serialized_string and post the results.

Cheers!

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.