0
votes

I was trying to make a template to show all used image in wordpress blog, and link to the post which has the image attached, like a gallery or portfolio page, but I can not get the link nor title to the post single page. I've made this far:

 <?php
$post_parent = get_post($post->ID, ARRAY_A);
$parent = $post_parent['post_parent'];
$paged = ( get_query_var( 'paged' ) ) ? get_query_var('paged') : 1;
$attachments = get_children( array( 'post_parent' => $post_id, 'post_type' => 'attachment', 'orderby' => 'menu_order ASC, ID', 'order' => 'DESC', 'paged' => $paged, 'posts_per_page' =>9,) ); 
?>

And the foreach:

<?php foreach($attachments as $id => $attachment) :
$img_title = $attachment->post_title;
$img_caption = $attachment->post_excerpt;
$img_description = $attachment->post_content;
?>

So I looked up the codex and found how to get the img url like this:

<?php if ( have_posts() ) : ?>
<li>
<?php $image_attributes = wp_get_attachment_image_src( $id, full ); // returns an array
if( $image_attributes ) {?> 
<a  href="<?php echo $image_attributes[0]; ?>"><img src="<?php echo $image_attributes[0]; ?>" alt="<?php echo $img_alt; ?>" title="<?php echo $img_title; ?>" /></a>
<?php
echo $post->post_parent;
?>
<p><a href="<?php
echo get_post($id)->post_parent; ?>">link</a></p>
<?php } ?>
</li>
<?php endif; ?>

<?php endforeach; ?>

These codes above works great, it shows all images attached in an ul li list.

Then I want to add a link to the parent POST in the loop, using something in the foreach like:

<p><a href="<?php echo get_post($id)->post_parent; ?>">Post link</a></p>

but it returns a link to nothing or returns a "0", if I "echo $id", it return the attachment id but not the Post ID (Post id is what I want).

Please how to get the parent post ID or simply get the post link and title in the loop above? Help!

Thank you!

1
Still cant fix this, can anyone give me a clue? - Duke

1 Answers

0
votes

Find the answer now. I use the normal query to get all posts, and that query search for the img tag in content( or its featured image) then show that image in loop, optionally to show excerpt below that image, then this template is done.

I was thinking about getting attachments in media library but it is not the right way, some media are not even attached to any posts so it’s a dead end.

But to query post and make that query select posts with “<img” is somewhat way more better than query attachments, and easy to understand too.