Question

I'd like some assistance modifying this code (source):

    <?php
    $args = array(
        'post_type' => 'attachment',
        'post_mime_type' => 'image',
        'numberposts' => 4,
        'post_status' => null,
        'post_parent' => any, // any parent
        ); 
    $attachments = get_posts($args);
    if ($attachments) {
        foreach ($attachments as $post) {
            setup_postdata($post);
            the_attachment_link($post->ID, false);
        }
    }
    ?>

Right now, it's getting querying all the image attachments from my WP install and displaying the latest 4 as their thumbnail versions. My problem is that the_attachment_link only allows for it to link to either the full-size image or the attachment page of the image. I'd like it to link to the post (and I can guarantee that each image is only attached to 1 post, if that would be an issue/concern).

I've tried using other functions like wp_get_attachment_image and wp_get_attachment_link but they end up displaying nothing (and no error either). Any help please?

Was it helpful?

Solution

Here is your solution:

<?php
$args = array(
    'post_type' => 'attachment',
    'post_mime_type' => 'image',
    'numberposts' => 4,
    'post_status' => null,
    'post_parent' => 'any', // any parent
);
$attachments = get_posts($args);
if ($attachments) {
    foreach ($attachments as $post) {
        setup_postdata($post);
        ?>
        <a href="<?php echo get_permalink($post->post_parent) ?>"><?php echo wp_get_attachment_image($post->ID) ?></a>
    <?php
    }
}
?>

Make sure $post->post_parent has a value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top