Search code examples
phpwordpressforeachposts

PHP foreach linking Wordpress


What is the best way for me to loop through this array of wordpress post ids and generate a linked image.

I currently have:

<?php
    $posts = array(1309,880,877,890,1741,1739,2017);

    print "<div class='row'>";
    foreach($posts as $post){
        $queried_post = get_post($post);
        echo "<a href='get_permalink( $post )'>";
        print "<div class='col-xs-2'>";      
            echo get_the_post_thumbnail($queried_post->ID, 'thumbnail');
        print "</div>"; 
        print "</a>";
    }
    print "</div>";                  
?>

I come from a ruby background and am pretty sure using print won't be the most effecient way to open and close html within the php call.

At the moment this doesn't work as it's not passing the post id correctly into the it's giving me this /get_permalink(%20880%20) in the URL.

Thanks in advance for any help.


Solution

  • You could use something like this:

    <?php
        $posts = array(1309,880,877,890,1741,1739,2017);
    ?>
       <div class='row'>
        <?php foreach($posts as $post): ?>
           <?php $queried_post = get_post($post); ?>
            <a href="<?php echo get_permalink( $post ) ?>">
            <div class='col-xs-2'>     
            <?php echo get_the_post_thumbnail($queried_post->ID, 'thumbnail'); ?>
            </div>
           </a>
        <?php endforeach; ?>
       </div>  
    

    This syntax makes use of syntactic sugar which you will come across often if you are working with WordPress.

    If you haven't already, it would be a great idea to check out the WordPress code reference, they provide examples of all their functions etc. and because the software is so widely used, they tend to stick to best practices (In most cases!), so it may be quite beneficial.