How do I use foreach to get content from a custom-field in multiple posts?

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.

Topic array php custom-field Wordpress

Category Web


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!


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;
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.