0

在 wordpress 主题中,我创建了自定义帖子类型。在此自定义帖子类型中,使用图像上传元框字段附加图像。为此,我可以创建任意数量的帖子(图像)。

在前端,在我的主模板中,我使用以下 wordpress 函数循环获取了这些图像:

    <?php

    global $post;
    $args = array(
    'post_type' =>'Imagespost',
    'numberposts' => -1,
    'order' => 'ASC' );

    $image_posts = get_posts($args); ?>

    <?php
        if($image_posts) { ?>

      <div id="bigImages">
      <ul class ="image-list">

           <?php

            foreach($image_posts as $post) : setup_postdata($post);

             // get attached image URL from image upload metabox field.
             $full_image = get_post_meta($post->ID, 'my_image', true);

           echo  '<a href=" ' . $full_image . '" class="playlist-btn">';
          ?>
              <?php endforeach;?>

            </ul>
       </div>

 <?php wp_reset_postdata(); ?>
 <?php } ?>

通过这种方式,我将每个附加图像存储为循环内的 $full_image 并将其用作 href 属性以进一步显示。同样,我只想将第一张图像或最后一张图像存储为变量取决于ORDER: as ascending (ASC) or descending (DESC).如何仅从自定义帖子类型中获取第一个或最后一个帖子的数据?

4

1 回答 1

2
$args = array(
    'post_type' =>'Imagespost',
    'numberposts' => -1,
    'posts_per_page' => 1,
    'order' => 'ASC' );

$image_posts = get_posts($args);

添加posts_per_page = 1。这只会返回一篇文章。

使用此查询两次,一次使用 ASC 顺序,一次使用 DESC 顺序。它只返回一个帖子。

或第二种解决方案是:

计算返回的帖子数。IE

$count = count($image_posts);
$image_posts[0] // return first ImagePost
$image_posts[$count-1] // returns last ImagePost.
于 2013-12-03T11:43:09.910 回答