I have a custom field attatched to a post that contains the following array of post titles...

a:6:{i:0;s:21:"Strawberry Cheesecake";i:1;s:15:"Flapjack";i:2;s:14:"Chocolate Muffin";i:3;s:27:"Apple Turnover";i:4;s:13:"Chocolate Cookie";i:5;s:13:"Shortbread";}

I am then outputing those post titles, searching for the related permalink and echoing them out using....

$speakerarray = get_post_meta($post->ID, 'cpt_food', true);

$foodname = $foodarray[$x];
$posts = get_posts(array('name' => $foodname, 'post_type' => 'food'));
$post = $posts[0];
$permalink = get_permalink($post->ID);
echo '<a href="';
echo $permalink;
echo '">';
echo $foodname;
echo '</a>';
echo "<br>";

Everything works fine apart from the last result, I have duplicated the issue with numerous items in the array etc.. and its always the last one that fails. It returns the permalink for the page I am currently on instead.

Can anyone see why?


You should use a foreach loop instead, as the count index isn't the best way to walk over an array.

$speakerarray = get_post_meta($post->ID, 'cpt_food', true);
foreach($speakerarray as $foodname) :
    $posts = get_posts(array('name' => $foodname, 'post_type' => 'food'));
    $post = $posts[0];
    echo '<a href="' . get_permalink( $post->ID ) . '>' . $foodname . '</a><br>';

I used a online tool for unserialize your data and it returned an error ?

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.