wp query – get all images from the wordpress media library with link to the post they are associated with

Question

I’m trying to get all the images from the wordpress media library with link to the post they are associated with.

I’m using this code, I get all the images, but the link is the link to the URL of the image, not the post they are associated with.

<?php

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

?>

using this code I get all the images, but without the link.

    <?php $wpb_all_query =

        new WP_Query(array('post_type' => 'attachment', 'post_status' => 'inherit', 'posts_per_page' => -1)); ?>

    <?php if ($wpb_all_query->have_posts()) : ?>

        <?php while ($wpb_all_query->have_posts()) : $wpb_all_query->the_post(); ?>
            <?php echo get_image_tag(get_the_ID(), '', '', 'none', 'medium'); ?>
        <?php endwhile; ?>

    <?php endif; ?>

can anybody help me with this ?

thanks

0
user2882154 5 months 2022-03-02T11:39:33-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse