0

I have for display attachmet on page this function

$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 ) {
                        // Assuming $attachment_id contains the ID of the attachment
                        $attachment_metadata = wp_get_attachment_metadata($attachment->ID);

                        if ($attachment_metadata) {
                            // Get file size in bytes
                            $file_size = filesize(get_attached_file($attachment->ID));

                            // Convert file size to human-readable format
                            $file_size_human = size_format($file_size);

                            // Get file type
                            $file_type = $attachment_metadata['mime_type'];
                            //$file_type = get_post_mime_type($attachment->ID);
                            $file_url = wp_get_attachment_url( $attachment->ID);
                            $filetype = wp_check_filetype( $file_url );

                            // Display file size and type
                            //echo '<p>File Size: ' . $file_size_human . '</p>';
                            //echo '<p>File Type: ' . $filetype['ext'] . '</p>';
                            $link = wp_get_attachment_link($attachment->ID);
                            echo '<li>' . $link . '( ' . $file_size_human . ', ' . $filetype['ext'] .')</li>';
```                        }

this work how I want, but now I have duplicated attachment on a page because one is server wit the_content() function. Which is bet way to modify dipslay content for page with my attachment link display.

1
  • some notes, exclude and other not style operators are extremely slow/expensive and very heavy on the server, it's much easier to add if ( $attachment->ID === get_post_thumbnail_id() ) { continue; } and could give a huge performance boost. The DB is optimised to give you what you want, it isn't optimised to exclude/hide what you don't want. Likewise set posts_per_page to a high value you know the server can handle, but never -1, your page can't display an infinite number of posts. Otherwise your Q appears to boil down to "how do I skip an attachment if it's already in the content?"
    – Tom J Nowell
    Commented Mar 21 at 11:15

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.