Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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....

<?php
$speakerarray = get_post_meta($post->ID, 'cpt_food', true);
$arrlength=count($foodarray);

for($x=0;$x<$arrlength;$x++)
{
$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?

share|improve this question
add comment

1 Answer

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

<?php
$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>';
endforeach;
?>

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

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.