【问题标题】:How to get first and last postdata from custom post type in wordpress?如何从wordpress中的自定义帖子类型获取第一个和最后一个postdata?
【发布时间】:2013-05-21 01:02:29
【问题描述】:

在 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). 如何仅从自定义帖子类型中获取第一个或最后一个帖子的数据?

【问题讨论】:

    标签: php custom-post-type wordpress


    【解决方案1】:
    $args = array(
        'post_type' =>'Imagespost',
        'numberposts' => -1,
        'posts_per_page' => 1,
        'order' => 'ASC' );
    
    $image_posts = get_posts($args);
    

    添加posts_per_page = 1。 这只会返回一个帖子。

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

    或者第二种解决方案是:

    计算返回的帖子数。即

    $count = count($image_posts);
    $image_posts[0] // return first ImagePost
    $image_posts[$count-1] // returns last ImagePost.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-11
      • 2016-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多