Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Get Posts Permalink From post_type=attachment WordPress

  • SOLVED

Hello!
So what I'm doing here is grabbing images attached to the post. Currently those images are linking to the attachment page itself. I need it to link to the actual post they belong to.

So instead of the image linking to <em>http://site.com/post-page/post_page_attachment_jpg/</em>, I need it to link to <em>http://site.com/post-page/</em>

My current code for this is below:



<?php
$attargs = array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'post_parent' => $post->ID);

$attachments = get_children($attargs);
if ($attachments) {
foreach ($attachments as $post) {
?>
<a style="float:left; margin-right:16px; width:120px; height:120px; overflow:hidden; display:block;" href="<?php the_permalink(); ?>"><img style="width:165px;" src="<?php echo wp_get_attachment_url($post->ID); ?>" alt="<?php the_title(); ?>" title="<?php the_title(); ?>" class="staff-img" /></a>

<?php break; //only display first image
}
}
?>

Answers (2)

2010-05-12

Lew Ayotte answers:

Try

$permalink = get_permalink($post->ID);

Also,

don't do:

foreach ($attachments as $post) {

do

foreach ($attachments as $attachment) {

That way you don't overwrite the $post variable... you'll need to adjust your other code too.


Lew Ayotte comments:

So basically the whole thing would look like:


<?php

$attargs = array(

'post_type' => 'attachment',

'post_mime_type' => 'image',

'post_parent' => $post->ID);



$attachments = get_children($attargs);

if ($attachments) {

foreach ($attachments as $attachment) {

?>

<a style="float:left; margin-right:16px; width:120px; height:120px; overflow:hidden; display:block;" href="<?php the_permalink($post->ID); ?>"><img style="width:165px;" src="<?php echo wp_get_attachment_url($attachment->ID); ?>" alt="<?php the_title(); ?>" title="<?php the_title(); ?>" class="staff-img" /></a>

<?php break; //only display first image

}

}

?>

2010-05-12

Andrzej answers:

<?php

$attargs = array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'post_parent' => $post->ID
);

$parent_permalink = get_permalink( $post->ID );

$attachments = get_children($attargs);

if ($attachments) {
foreach ($attachments as $post) {
?><a style="float:left; margin-right:16px; width:120px; height:120px; overflow:hidden; display:block;" href="<?php echo $parent_permalink; ?>"><?php
?><img style="width:165px;" src="<?php echo wp_get_attachment_url($post->ID); ?>" alt="<?php the_title(); ?>" title="<?php the_title(); ?>" class="staff-img" /></a><?php
break; //only display first image
}
}

?>