How can I get the thumbnail from a WP_Post object? - php

I'm trying to Loop over a bunch of pages under a certain taxonomy. The looping part works great, and I get all of the pages I need (nicely wrapped in WP_Post objects).
However, now I'm facing a different kind of problem. I want to include the page's thumbnail as set in the editor. I've tried any combination of get, the, thumbnail, featured, image, _, -, I could think of, to no avail.
The WP_Post object is rather new, and documentation is lacking.
Can anyone shed light on this mystery? My goal is to eventually show a bunch of <figure> elements, containing an image, a title, and a short description of each object.

The following is just a proof of concept in form of shortcode. It dumps a code block with all posts that have a Featured Image.
Function reference: has_post_thumbnail, get_the_post_thumbnail
add_shortcode( 'all-post-thumbs', 'so_14007170_dump_post_thumbs' );
function so_14007170_dump_post_thumbs( $atts, $content )
{
// Query
$posts = get_posts( array(
'post_type' => 'post',
'numberposts' => -1,
'post_status' => 'publish'
) );
// Build an array of post thumbnails
$thumbs = array();
foreach( $posts as $post)
{
if( has_post_thumbnail( $post->ID) )
$thumbs[] = array( $post->post_title, htmlentities(get_the_post_thumbnail( $post->ID ) ) );
}
// Build output and return
$echo = '<pre>'. print_r( $thumbs, true ) . '</pre>';
return $echo;
}
Result in frontend:
Posts with featured image:

Not sure what do you want but if you want to get all images of a certain page then you can use
$parent='your page id';
$args=array(
'post_parent' => $parent,
'post_type' => 'attachment',
'post_mime_type' => 'image',
'orderby' => 'menu_order',
'order' => 'ASC',
'numberposts' => -1
);
$images = get_children($args);
You can paste this code in your loop and if you provide the appropriate page_id as parent then you'll get all images as an array in the $images and can run a loop.
Read more at Codex.
Update:
To get only the featured image you can use
echo get_the_post_thumbnail('page id here', 'thumbnail');
Read more at Codex.

if ( have_posts() ) : while ( have_posts() ) : the_post();
// stuff before thumbnail
$thumbnail_args = array();
// insert whatever thumbnail args you want
echo get_the_post_thumbnail();
// stuff after thumbnail
endwhile; else:
echo "<h2>Sorry, nothing to see here.</h2>";
endif
Unfortunately, the WP_Post methods are named really poorly. Most methods which interact with the Post need to have some arrangement of '_' and 'post' added to them.

Related

Wordpress wp_get_attachment_image doesn't show images for every post

wp_get_attachment_image() gets images only for 2 out of 5 posts.
I am new to WordPress, I am making theme where main page only shows images (attachments) from posts. Posts are all in the same manner - title, paragraph, and gallery. Each of them have category assigned to it.
Tried to fix the problem in many ways but none seem to be working. I've dumped every post and it seems that
$postyMarkiQq = new WP_Query( array( 'category_name' => 'marki' ) );
$posty = $postyMarkiQq->posts;
gets information properly.
I've tried using get_attached_media('', $post->ID) but it returns same results.
I've tried putting the main part of the code to function.
<?php
$postyBrandQ = new WP_Query( array( 'category_name' => 'brand' ) );
$posty = $postyBrandQ->posts;
foreach($posty as $post) {
echo $post->ID;
?>
<div class="category">
<?php
echo get_the_title( $post->ID );
$args = array(
'post_parent' => $post->ID,
'post_type' => 'attachment',
'post_mime_type' => 'image',
'posts_per_page' => -1,
'orderby' => 'menu_order',
'order' => 'ASC',
);
$attachments = get_children( $args );
foreach ( $attachments as $attachment ) {
echo wp_get_attachment_image($attachment->ID);
}
wp_reset_postdata();
?>
</div>
<?php
}
?>
I don't have any idea why wouldn't this work.
Would really appreciate help.
Thanks!
You probably shouldn't be querying by post parent. Attachments are only given post parents based on the page you are currently viewing when you upload the item to the media library. If you click media, and upload images, the images won't have a post parent, even if you go to a post (or page) later on, and set that image as the featured image.
So, I don't know the exact context of your question, but perhaps get_post_thumbnail_id( $post->ID ) will be the answer you are looking for. This will return the attachment ID of the featured image, then you can use wp_get_attachment_image_src() (pass in the attachment ID probably), which will return you an array. Print the array, in there somewhere you will find the URL.

Display child post on parent post page in wordpress

Our current website is using custom posts with parent/child posts.
When viewing a (parent) post, a plugin is used to pull its child posts and those are displayed in a tab on the page.
We are using a new version of that custom theme on several websites now and are no longer using parent/child relationship. Instead we have metaboxes in our custom posts types and all additional information can be filed right there.
I wanted to update this particular website with the latest version of the theme, but since it's using parent/child relationship I wanted to add a few lines of code to the theme in order to achieve the same result and keep the old posts the way they are instead of modifying them all.
Here's what I want to do : I want a very simple way to display all child post (in order) on a parent post page.
I've found a few ideas here and there but none seems to be working so far. (Here's one for example : http://www.wpbeginner.com/wp-tutorials/how-to-display-a-list-of-child-pages-for-a-parent-page-in-wordpress/ as well as this one https://wordpress.stackexchange.com/questions/153042/how-to-display-list-of-child-pages-with-parent-in-wordpress). I don't know if it has to do with the fact that i'm using post rather than pages.
I don't want a list of the child post but rather display the content of those directly. Was thinking the best way to achieve this might be to create a function to retrieve the child post and then echoing the result in the template. That way without having to change our theme it could work with our different website.
EDIT :
So far here's what i've tried within single.php :
$query = new WP_Query( array(
'post_parent' => get_the_ID(),
));
while($query->have_posts()) {
$query->the_post();
the_content(); //Outputs child's content as it is
}
wp_reset_query();`
I then changed the code to :
$new_args = array(
'order' => 'ASC',
'post_parent' => get_the_ID()
);
$new_query = new WP_Query( $new_args);
if ($new_query->have_posts() ) {
while($new_query->have_posts() ) {
$new_query->the_post();
the_content();
}
wp_reset_query();
}
and then since it didn't work either i've changed it to :
$children = get_children( array('post_parent' => get_the_ID()) );
foreach ( $children as $children_id => $children ) {
the_title();
the_content();
}
The latest seems to be able to return some results, it "knows" that the current post has children in it but i'm displaying the title and content of the current post. I'm pretty sure I shouldn't be using the_content() in here.
Ok, try something like this inside your post template within the loop. It should help you to output child posts inside particular post.
<?php
/Somwhere in the loop/
$query = new WP_Query( array(
'post_parent' => get_the_ID(),
'posts_per_page' => 3, //shows only 3 children. If you want to show all of them, comment this line
));
while($query->have_posts()) {
$query->the_post();
/*Output the child markup here*/
the_content(); //Outputs child's content as it is
}
wp_reset_query();
?>
UPDATED:
Ok, you can try to use post_parent__in & array of IDs, this should work too.
<?php
/Somwhere in the loop/
$query = new WP_Query( array(
'post_parent__in' => array(get_the_ID()),
'posts_per_page' => 3, //shows only 3 children. If you want to show all of them, comment this line
));
while($query->have_posts()) {
$query->the_post();
/*Output the child markup here*/
}
wp_reset_query();
?>
If not, here is the way to output contents of the posts you got using get_children function. This should probably work too
<?php
$children = get_children( array('post_parent' => get_the_ID()) );
foreach ( $children as $children_id => $child ) {
echo $child->post_title;
echo str_replace( ']]>', ']]>',apply_filters( 'the_content', $child->post_content )); //mimic the_content() filters
//echo $child->post_content; // if you do not need to filter the content;
}
?>
/* Fetch only one level child pages of a parent page */
$pages = get_pages(
array (
'parent' => 'parent_id',
'post_type => 'page',
'post_status' => 'publish',
);
$ids = wp_list_pluck( $pages, 'ID' );
/* Return page IDs in array format */
/* You can retrieve "post_title", "guid", "post_name" instead of "ID"
/* Fetch all child pages of a parent page*/
$pages = get_pages(
array (
'parent' => '-1',
'child_of' => 'parent_id', /* Return child of child for current page id */
'post_type => 'page',
'post_status' => 'publish',
);
$ids = wp_list_pluck( $pages, 'ID' );
/* Return page IDs in array format */
/* You can retrieve "post_title", "guid", "post_name" instead of "ID" */

Get images from gallery in taxonomy

There seems to be several answers to similar questions but I have not yet found one working for me.
I have a custom post-type called entertainement. entertainement has a taxonomy called ent_categories.
One of the ent_categories is called Event
Each Event has a gallery and I am trying to make a query that will return the latest 10 images that has been added to any of the CPT entertainment with the category Event.
Im hoping to receive a list of urls in an array.
From what I read here something like this should do the trick:
$arg = array(
'post_status' => 'inherit',
'posts_per_page' => -1,
'post_type' => 'attachment',
);
$arg['tax_query'] = array(
array(
'taxonomy' => 'ent_categories',
'field' => 'name',
'terms' => array( 'Event' ),
),
);
$the_query = new WP_Query( $arg );
var_dump($the_query);
The var_dump($the_query); displays a lot of things but no images?
Any tips on this one?
Thank you
EDIT:
I just saw that I can do this:
function pw_show_gallery_image_urls( $content ) {
global $post;
// Only do this on singular items
if( ! is_singular() )
return $content;
// Make sure the post has a gallery in it
if( ! has_shortcode( $post->post_content, 'gallery' ) )
return $content;
// Retrieve all galleries of this post
$galleries = get_post_galleries_images( $post );
$image_list = '<ul>';
// Loop through all galleries found
foreach( $galleries as $gallery ) {
// Loop through each image in each gallery
foreach( $gallery as $image ) {
$image_list .= '<li>' . $image . '</li>';
}
}
$image_list .= '</ul>';
// Append our image list to the content of our post
$content .= $image_list;
return $content;
}
add_filter( 'the_content', 'pw_show_gallery_image_urls' );
This result in that all the gallery images urls get displayed below the images in the gallery.
Maybe this function could be called from a page instead than from functions.php?
You were on the right track, but you're querying for posts of type attachment with a term of the ent_categories taxonomy which only applies to entertainement posts, so there won't be any of them as you'll see if you:
var_dump($the_query->posts);
If you dump all $the_query you'll see lots of things because it's a WP_Query object.
You need to query your entertainement posts: (Be careful because you have a typo in your slug!)
$arg = array(
'posts_per_page' => -1,
'post_type' => 'entertainement',
);
$arg['tax_query'] = array(
array(
'taxonomy' => 'ent_categories',
'field' => 'name',
'terms' => 'Event',
),
);
$the_query = new WP_Query( $arg );
Then you can iterate the posts and get the gallery items like this:
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
if (get_post_gallery()) :
echo get_post_gallery();
print_r(get_post_gallery_images());
endif;
}
/* Restore original Post Data */
wp_reset_postdata();
}
get_post_gallery_images() will get you an array of the URL's of gallery images
get_post_gallery() will get you actual HTML to print the gallery.

Trying to get an attachment from a post in a Wordpress loop but getting all, from all posts

First of all - this is a question mainly about the loop™. I'm also having problems with the attachment thing, but that is somehow secondary since there are snippets around there I think could be useful.
Ok, so this is want I want to do in a front page:
get 7 posts from custom post type 'portfolio'
only with the first one, get an specific attachment (in any possible way, be it filename, order in the media manager... whatever is the best, more clean way)
with the other 6, just get the_post_thumbnail() and little more.
Now, I have this:
<?php
$args = array (
'post_type' => 'portfolio',
'order' => 'DESC',
'posts_per_page' => 7
);
$query = new WP_Query( $args );
$first_post = true; /* we will take the latest work first */
?>
<?php if ( $query->have_posts() ) : ?>
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
<?php
if ($first_post):
$first_post = false;
?>
<div> /* This is the div for the first item */
<?php /* let's take the first attachment */
$args = array(
'post_type' => 'attachment',
'numberposts' => 1,
'order' => 'DESC'
);
$attachments = get_posts( $args );
if ( $attachments ) :
foreach ( $attachments as $attachment ) :
echo wp_get_attachment_image( $attachment->ID, 'full' );
endforeach;
endif;
?>
</div>
<?php else: ?>
/* Do something with the other 6 posts and their post_thumbnail */
<?php endif ?>
<?php endwhile; ?>
And now for the questions:
First and foremost: if I set 'numberposts' to all (-1) when trying to recover the attachment, I get ALL attachments from ALL 'portfolio' posts. Shouldn't I be interacting only with the current post (the_post())? I can't quite grasp the concept of the loop here, this is the main question.
That code won't get me the first attachment, even if it's placed in the first place in that post's media manager.
Should I go for secondary or nested loops? I've read and re-read the codex and other tutorials but still can't wrap my head around it.
Many thanks!
used this code :
$attachments = get_posts( array(
'post_type' => 'attachment',
'posts_per_page' => -1,
'post_parent' => $post->ID,
'exclude' => get_post_thumbnail_id()
) );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
$class = "post-attachment mime-" . sanitize_title( $attachment->post_mime_type );
$thumbimg = wp_get_attachment_link( $attachment->ID, 'thumbnail-size', true );
echo $thumbimg;
}
}
User Shakti Patel gave me the key to the answer, but didn't really answer my question about the loop so here it goes:
The problem was with get_posts. It actually runs a parallel query to the main one without taking into account the current step of the loop. So we have to ask it for the attachments of the current post, which since we're in the loop is stored within $post->ID. So knowing that, we have to request the first attachment for the current post like this:
$args = array(
'post_type' => 'attachment',
'posts_per_page' => 1,
'post_parent' => $post->ID,
'exclude' => get_post_thumbnail_id()
);
$attachments = get_posts( $args );
That way we specify what is the post from which we'll get the first attachment, and while we're on it, exclude the post thumbnail.
I don't know if this is the best way since we're already on a loop and we shouldn't need a new query, shouldn't we be able to retrieve that attachment without the get_posts bit?
Anyway, for more info on get_posts (read while not half asleep): http://codex.wordpress.org/Template_Tags/get_posts

How to exclude posts with no images in a wordpress query_post function?

The query below runs a featured carousel on my site. I want the carousel to only display post that contain an image. I've searched everywhere and cannot find a solution. Please help!
query_posts(array('post_type' => 'ad_listing', 'post_status' => 'publish', 'orderby' => 'rand'));
I ran into this same thing while developing my own theme.
This is how I solved it.
Start by adding the featured image capability in your functions.php.
if (function_exists('add_theme_support')) {
add_theme_support('post-thumbnails');
}
This allows you to select a featured image for each post.
With the featured image function available you can use the following function to detect if a post has a featured image...in loop form:
$args = array(
'post_type' => 'ad_listing'
);
query_posts($args);
if ( have_posts() ) :
while ( have_posts() ) : the_post();
if ( has_post_thumbnail() ) { //For featured images
//For post images/attachments
ob_start();
the_id();
$postID = ob_get_clean();
$args = array(
'numberposts' => 1,
'order'=> 'ASC',
'post_mime_type' => 'image',
'post_parent' => $postID,
'post_status' => null,
'post_type' => 'attachment'
);
$images =& get_children($args);
if ( empty($images) ) {
//What to do without images
}
else {
//What to do with images
}
}
endwhile;
else :
//What happens when no posts are found
endif;
Hope this helps.
You won't be able to do that using query_posts. You'll have to do it in the loop.
Look at get_children() and especially the example of how to Show the first image associated with the post.

Categories