Skid Kadda
Skid Kadda

Reputation: 482

get_post_meta returns an array when third parameter is set to true

[edit] TLDR: The answer: don't use echo, but print_r

I have tried the following to get the meta value as a string, instead of an Array. The third value is set to true, so this should result as a string.

<?php

    // The data
    $projects = $wpdb->get_results( "SELECT * FROM $wpdb->posts" ); 


    // Loop them
    foreach ( $projects as $project ) 
    {
        // Get the meta
        $metas = get_post_meta( $project->ID,'bc_invited', true );

        // This is rendering
        echo '<h2>' . $project->post_title . '</h2>';

        foreach($metas as $meta){
            // This is not rendering
            echo $meta . '<br/>';
        }

    }
?>

Why am I not seeing what I expected?

Upvotes: 0

Views: 1531

Answers (1)

Omar Freewan
Omar Freewan

Reputation: 2678

the get_post_meta function receve the the third parameter as (boolean) (optional) If set to true then the function will return a single result, as a string.

If false, or not set, then the function returns an array of the custom fields. This may not be intuitive in the context of serialized arrays. If you fetch a serialized array with this method you want $single to be true to actually get an unserialized array back. If you pass in false, or leave it out, you will have an array of one, and the value at index 0 will be the serialized string. Default: false

 <?php $meta_values = get_post_meta($post_id, $key, $single); ?>

now your problem is you returned the meta as array and used the echo which caused the problem you have to use print_r instead to see the result

Upvotes: 1

Related Questions