How to get all attachments for a wordpress post? - php

I am currently attempting to get all the attachments that are attached to each individual post on WordPress and allow a user to download the attachments.
I have looked into the get_attached_media() function in WordPress but I am not sure how to make the files downloadable once I get the media.

Try this code this may help you:
With below code you can fetch all type of media attachment if you need particular media type then you can add one more args 'post_mime_type' => 'image'
<?php if ( $post->post_type == 'post' && $post->post_status == 'publish' ) {
$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 ) {
$class = "post-attachment mime-" . sanitize_title( $attachment->post_mime_type );
$thumbimg = wp_get_attachment_link( $attachment->ID, 'thumbnail-size', true );
echo '<li class="' . $class . ' data-design-thumbnail">' . $thumbimg . '</li>';
}
}
}
?>
Another way you can achieve this:
$media = get_attached_media('image', get_the_ID()); // Get image attachment(s) to the current Post
print_r($media);

Related

Finding attachment page URL of/from an image url

I'm using the below code to get all image URL's attached to a post.
global $post;
$thumbnail_ID = get_post_thumbnail_id();
$images = get_children( array('post_parent' => $post_id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID') );
if ($images) :
foreach ($images as $attachment_id => $image) :
$img_alt = get_post_meta($attachment_id, '_wp_attachment_image_alt', true); //alt
if ($img_alt == '') : $img_alt = $image->post_title; endif;
$big_array = image_downsize( $image->ID, 'large' );
$img_url = $big_array[0];
endforeach; endif; }
The output I get is something like this:
https://www.example.com/wp-content/uploads/2019/01/image.gif
What I need to find is the attachment page URL for this image which will be something like this https://www.example.com/post-name/image-22
I tried using wp_get_attachment_image, but the output wasn't what I needed.
any idea how can i do that?
You are looking for get_attachment_link to return a pretty link you need to make sure your permalink structure is set to pretty links.
https://codex.wordpress.org/Function_Reference/get_attachment_link
Example from page:
<?php
$attachment_id = 1; // ID of attachment
$attachment_page = get_attachment_link( $attachment_id );
?>
<?php echo get_the_title( $attachment_id ); ?>

Extracting images from an array

Hello with the code bellow i am getting some content.
How is possible with php simple html dom to get all the img src?
my code:
foreach($html->find('div[class=post-single-content box mark-links]') as $table)
{
$arr44[]= $table->innertext ;
}
div with class post-single-content box mark-links contains text and images
Try this :
<?php if ( $post->post_type == 'data-design' && $post->post_status == 'publish' ) {
$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 ) {
$class = "post-attachment mime-" . sanitize_title( $attachment->post_mime_type );
$thumbimg = wp_get_attachment_link( $attachment->ID, 'thumbnail-size', true );
echo '<li class="' . $class . ' data-design-thumbnail">' . $thumbimg . '</li>';
}
}
}
?>

Wordpress - display Media Library items based on category

Just like the title says, I'm trying to display only the items in the Media Library that are under a particular category. Whether they're attached to anything or not.
Currently I can get all images, but I'm not sure how to narrow it down to certain categories.
Here's what I have so far:
<select name="event-dropdown" onchange="document.location.href=this.options[this.selectedIndex].value;">
<option value=""><?php echo esc_attr(__('Select Event')); ?></option>
<?php
$args = array(
'hide_empty' => 0,
);
$categories = get_categories($args);
foreach ($categories as $category) {
$option = '<option value="?cat='.get_cat_ID($category->cat_name).'">';
$option .= $category->cat_name;
$option .= ' ('.$category->category_count.')';
$option .= '</option>';
echo $option;
}
?>
</select>
<?php
$query_images_args = array(
'post_type' => 'attachment',
'post_mime_type' =>'image',
'post_status' => 'inherit',
'posts_per_page' => -1,
);
$query_images = new WP_Query($query_images_args);
if($_GET['cat']){
// not sure what to do here yet
}else{
// this part works fine
foreach ( $query_images->posts as $image) {
echo wp_get_attachment_image($image->ID);
}
}
?>
Can someone enlighten me on how/if this can be done. All I've been able to find is stuff relating to attached images or post images. I just want to pull them directly from the Library.
EDIT Tags would work too. It doesn't have to be category.
unless you're adding a custom meta tag to each image in your media library, your query won't work.
A possible solution
e.g. create a post, name it something relevant, tag all the categories you want this post to be associated with, now dump all the images you want to show into this post.
you can use this query to bump out the post & category terms you want to show, along with the images attached to the post(s).
<?php
$args = array (
'post_type' => 'post',
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => 'your-cat-name-here'
)
)
);
$custom_query = new WP_Query( $args );
if ( $custom_query->have_posts() ):
while ( $custom_query->have_posts() ) :
$custom_query->the_post();
// Do stuff with the post content.
$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 ) {
$class = "post-attachment mime-" . sanitize_title( $attachment->post_mime_type );
$thumbimg = wp_get_attachment_link( $attachment->ID, 'thumbnail-size', true );
$image_title = $attachment->post_title;
$caption = $attachment->post_excerpt;
$description = $image->post_content;
//print_r($attachment);
echo '<div class="thumbnail"><figure><img src="'.wp_get_attachment_url($attachment->ID).'" /></figure></div>';
}
//End
echo '</div>';
}
endwhile;
else:
// we can insert something if Nothing found.
echo "<h2>Sorry, but there's nothing here.</h2>";
endif;
wp_reset_query();
?>

Change post thumbnail on using front end post edit form [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I'm trying to get the post thumbnail to change if a user selects a new file on a front end post edit screen. This is similar to the code I use to upload data and set the post thumbnail on a front end add new post form:
<?php
$query = new WP_Query( array( 'post_type' => 'properties', 'posts_per_page' => '-1' ) );
if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();
if(isset($_GET['post'])) {
if($_GET['post'] == $post->ID)
{
$current_post = $post->ID;
$content = get_the_content();
$price = get_post_meta($post->ID, 'shru_price', true);
$address = get_post_meta($post->ID, 'shru_address', true);
$thumbnail = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-image' );
}
}
endwhile; endif;
wp_reset_query();
global $current_post;
$postContentError = '';
if ( isset( $_POST['submitted'] ) && isset( $_POST['post_nonce_field'] ) && wp_verify_nonce( $_POST['post_nonce_field'], 'post_nonce' ) ) {
if ( trim( $_POST['postContent'] ) === '' ) {
$postContentError = 'Please enter a description of this property.';
$hasError = true;
}
$post_information = array(
'ID' => $current_post,
'post_content' => $_POST['postContent'],
'post_type' => 'properties',
'post_status' => 'publish'
);
$post_id = wp_update_post($post_information);
function upload_user_file( $file = array() ) {
global $post_id;
require_once( ABSPATH . 'wp-admin/includes/admin.php' );
$file_return = wp_handle_upload( $file, array('test_form' => false ) );
if( isset( $file_return['error'] ) || isset( $file_return['upload_error_handler'] ) ) {
return false;
} else {
$filename = $file_return['file'];
$attachment = array(
'post_mime_type' => $file_return['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit',
'guid' => $file_return['url']
);
$attachment_id = wp_insert_attachment( $attachment, $file_return['url'], $post_id );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
if( 0 < intval( $attachment_id ) ) {
return $attachment_id;
}
}
return false;
}
if( ! empty( $_FILES ) ) {
foreach( $_FILES as $file ) {
if( is_array( $file ) ) {
$attachment_id = upload_user_file( $file );
}
}
}
$propertyfor = $_POST['propertyfor'];
$propertytype = $_POST['propertytype'];
$bedrooms = $_POST['bedrooms'];
if($post_id) {
// Update Custom Meta
update_post_meta($post_id, 'shru_price', esc_attr(strip_tags($_POST['shru_price'])));
update_post_meta($post_id, 'shru_address', esc_attr(strip_tags($_POST['shru_address'])));
update_post_meta($post_id, '_thumbnail_id', $attachment_id );
wp_set_object_terms( $post_id, $propertyfor, 'propertyfor' );
wp_set_object_terms( $post_id, $propertytype, 'propertytype' );
wp_set_object_terms( $post_id, $bedrooms, 'bedrooms' );
// Redirect
wp_redirect(home_url('/listings'));
exit;
}
}
?>
The only difference is that in the code above I am trying to use:
update_post_meta($post_id, '_thumbnail_id', $attachment_id );
instead of:
set_post_thumbnail($post_id, $attachment_id);
For some reason, on the post edit screen the image file does not even upload. When I use update post meta, it removes the old thumbnail, so I guess it's doing it's job there, but since the file isn't uploading it cannot replace it with a new one. The confusion is why the file uploads using the upload_user_file function on the add new post screen but not the edit post screen.
Any ideas?

Wordpress: Get images of current post

i'm trying to get all images of a post using this method:
$args = array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => null,
'post_parent' => $post->ID
);
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
$images[] = wp_get_attachment_image_src( $attachment->ID, ATTACHMENT_IMAGE_SIZE );
}
return $images;
}
unfortunately, this will get all images ever uploaded, not just those associated to the current post. i found this post using *get_children*, but it doesn't work either. any ideas?
ps: i running the code when a post created/updated
You can try
<?php
$attachments = get_posts( array(
'post_type' => 'attachment',
'posts_per_page' => -1,
'post_parent' => $post->ID,
) );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
$class = "post-attachment mime-" . sanitize_title( $attachment->post_mime_type );
$thumbimg = wp_get_attachment_link( $attachment->ID, 'thumbnail-size', true );
echo '<li class="' . $class . ' data-design-thumbnail">' . $thumbimg . '</li>';
}
}
?>
Read more here.
Make sure $post->ID is not empty.
If this is still not working you can try Extracting Images from the Page / Post content. More details here
Try it by adding a hook in your functions.php to fire after post/page has been created/updated and wrap your code inside that function as given bellow
add_action( 'save_post', 'after_post_save' );
function after_post_save( $post_id ) {
if ( 'post' == get_post_type($post_id) ) // check if this is a post
{
$args = array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => null,
'post_parent' => $post_id
);
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
$images[] = wp_get_attachment_image_src( $attachment->ID, ATTACHMENT_IMAGE_SIZE );
}
return $images; // End of function and nothing happens
}
}
}
Remember, basically it'll do nothing by returning the $images array at the end of your function unless you do something with the images.
Note: The wp_get_attachment_image_src function returns an array which contains
[0] => url // the src of image
[1] => width // the width
[2] => height // the height
So in your $images array it will contain something like this
array(
[0] => array([0] => url, [1] => width, [2] => height), // first image
[1] => array([0] => url, [1] => width, 2] => height) // second image
);

Categories