PHP foreach 链接 Wordpress
PHP foreach linking Wordpress
我循环遍历这个 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>
此语法使用了 syntactic sugar,如果您使用 WordPress,您会经常遇到它。
如果您还没有,最好查看 WordPress code reference,它们提供了所有功能的示例等,并且由于该软件使用如此广泛,它们往往会坚持下去最佳实践(在大多数情况下!),因此它可能非常有益。
你应该利用 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();
我循环遍历这个 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>
此语法使用了 syntactic sugar,如果您使用 WordPress,您会经常遇到它。
如果您还没有,最好查看 WordPress code reference,它们提供了所有功能的示例等,并且由于该软件使用如此广泛,它们往往会坚持下去最佳实践(在大多数情况下!),因此它可能非常有益。
你应该利用 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();