Reputation: 343
In the wordpress theme I have created custom post type. In this custom post type images are attached using image upload metabox field. For this I can create any number of posts( images).
At the front end ,inside my main template I got those images in loop using following wordpress functon:
<?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 } ?>
In this way I am storing each attached image as $full_image inside loop and using it as href attribute for further display . same way I want to store only first image or last image as a variable depends if ORDER: as ascending (ASC) or descending (DESC).
How can I grab only the data from first or last post from custom post type?
Upvotes: 0
Views: 3690
Reputation: 1325
$args = array(
'post_type' =>'Imagespost',
'numberposts' => -1,
'posts_per_page' => 1,
'order' => 'ASC' );
$image_posts = get_posts($args);
Add posts_per_page = 1. This returns only one post.
Use this query twice one with order ASC and one with order DESC. And it returns only one post.
Or second solution is :
Count number of posts returned. i.e
$count = count($image_posts);
$image_posts[0] // return first ImagePost
$image_posts[$count-1] // returns last ImagePost.
Upvotes: 2