0

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.

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

You should make use of WP_Query class.

# The Query
$the_query = new WP_Query( $args );

# Open div.row
echo '<div class="row">';

# The Loop
if ( $the_query->have_posts() ) {
    while ( $the_query->have_posts() ) {

        $the_query->the_post(); ?>

        <a href="<?php the_permalink(); ?>">
            <div class="col-xs-2"><?php the_post_thumbnail( 'medium' ); ?></div>
        </a>

<?php }
} else {
    # no posts found
}

# Close div.row
echo '<div>';

# Restore original Post Data
wp_reset_postdata(); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.