对我来说,循环使用这个wordpress post id数组并生成链接图像的最佳方式是什么。
我目前有:
<?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>";
?>
我来自ruby背景,非常确信使用print不会是在php调用中打开和关闭html的最有效方法。
目前,这不起作用,因为它没有正确地将post-id传递到中。它在URL中给了我这个/get_permalink(%20880%20)
。
提前感谢您的帮助。
您可以使用这样的东西:
<?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>
这种语法利用了语法糖,如果你在使用WordPress,你会经常遇到这种糖。
如果你还没有,那就去看看WordPress的代码参考吧,它们提供了所有功能的示例等。由于该软件的使用非常广泛,他们倾向于坚持最佳实践(在大多数情况下!),所以这可能非常有益。
您应该使用WP_Query类。
# 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();