【问题标题】:PHP foreach linking WordpressPHP foreach 链接 Wordpress
【发布时间】:2015-03-19 17:23:24
【问题描述】:

对我来说,遍历这个 wordpress 帖子 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>";                  
?>

我来自红宝石背景,我很确定使用 print 不会是在 php 调用中打开和关闭 html 的最有效方式。

目前这不起作用,因为它没有将帖子 ID 正确传递到它在 URL 中给我这个/get_permalink(%20880%20)

提前感谢您的帮助。

【问题讨论】:

    标签: php wordpress foreach posts


    【解决方案1】:

    你可以这样使用:

    <?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,他们提供了所有功能的示例等。由于该软件被广泛使用,他们倾向于坚持最佳实践(在大多数情况下!),所以它可能是非常有益的。

    【讨论】:

      【解决方案2】:

      你应该使用 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(); 
      

      【讨论】:

        猜你喜欢
        • 2014-04-21
        • 2013-09-04
        • 2016-04-26
        • 2016-09-04
        • 1970-01-01
        • 2021-05-07
        • 2014-06-26
        • 2016-06-15
        • 1970-01-01
        相关资源
        最近更新 更多