I want to create a custom page that will display let’s say 20 latest galleries / page – but only the first image from the gallery, not all of them. something like this: http://www.autoblog.it/gallerie/
I’ve done this:
<?php
$args = array(
'post_type' => 'attachment',
'posts_per_page' => 10,
'post_parent' => $postid,
'numberposts' => 1,
'paged' => $paged,
);
$attachments = get_posts($args);
if ($attachments) {
foreach ($attachments as $attachment) {
echo the_attachment_link($attachment->ID, false, false, true )
echo get_the_title(); }
}?>
it works but what it does is to display latest 10 images, not latest 10 galleries, so first image from each gallery.
Please help
Thank you
Getting the latest posts with a gallery is simple: search for posts with the string
'[gallery'
.Getting the first image from each gallery is harder, because you have to render the
gallery
shortcode. I would not use the default handler, it does much more than we need here. It would waste too much time.Step by step â¦
The main function
Letâs start with a function to retrieve a list of latest gallery posts with two parameters: the number of posts and a formatting helper:
As you can see we need a class
T5_Gallery_Image_Extractor
to build the list and a formatting function to create the Markup. I havenât put the formatter into the gallery extractor to stay flexible: You might use the function in a widget or in a shortcode with different formatters.The class T5_Gallery_Image_Extractor
The class constructor expects a list of posts. It doesnât care about how we got that list, so we can build is manually with a completely different main function.
Internally, it replaces the default shortcode handler for
gallery
with a simplified version to get just the first image from the first gallery in a post.The public method
get_results()
returns an array like this:So we get the post URL, the image markup and the post title for each post with a gallery.
The code, sorry, no time for comments, maybelater. 🙂
The formatter
Dead simple: just convert the array from above into a HTML list.
Now we can use the main function wherever we need it:
And the result is a nice list of the latest ten posts with a gallery, the first image from the first gallery is used as link text.
Visual formatting is left to the stylesheet:
Hi and thank you for the code…
I also made a shorter code that acually works ,,
here it is:
This actually work perfect. The only question is now how can i do pagination ???
Thank you very much.