Wordpress: Get images of current post - php

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
);

Related

Wordpress: Display image attachments from child pages of a specific page

I am trying to display all image attachments on the child pages of a specific parent page, i.e. all the pictures on Pages 10, 11 and 12.
Projects (Page ID: 5)
- Project 1 (Page ID: 10)
- Project 2 (Page ID: 11)
- Project 3 (Page ID: 12)
This is what I have so far, and it works to display all images on the site:
<?php
$args = array(
'post_parent' => 0,
'post_type' => 'attachment',
'numberposts' => -1
);
$images = get_children( $args );
if ( empty($images) ) {
// no attachments here
} else {
foreach ( $images as $attachment_id => $attachment ) {
echo wp_get_attachment_image( $attachment_id, 'full' );
}
}
?>
However, if I add the post parent ID (5), nothing comes up:
<?php
$args = array(
'post_parent' => 5,
'post_type' => 'attachment',
'numberposts' => -1
);
$images = get_children( $args );
if ( empty($images) ) {
// no attachments here
} else {
foreach ( $images as $attachment_id => $attachment ) {
echo wp_get_attachment_image( $attachment_id, 'full' );
}
}
?>
Any suggestions would be really helpful!
I think get_children() return objects from a single parent post or all (passing 0 as value).
You may try a nested foreach to get all post children first, then query attachment page by page. Here is an untested sample, but it gives you an idea:
<?php
$subpages_args = array(
'post_parent' => 5,
'post_type' => 'page',
'numberposts' => -1
);
$sub_pages = get_children( $subpages_args );
foreach( $sub_pages as $subpage_id => $sub_page) {
$args = array(
'post_parent' => subpage_id,
'post_type' => 'attachment',
'numberposts' => -1
);
$images = get_children( $args );
if ( empty($images) ) {
// no attachments here
} else {
foreach ( $images as $attachment_id => $attachment ) {
echo wp_get_attachment_image( $attachment_id, 'full' );
}
}
}
?>
Good luck :)
Here is an SQL Query based solution. Copy following function in your theme's functions.php
function get_children_page_attachments($parent_id) {
global $wpdb;
// just a precautionary typecast and check
$parent_id = intval( $parent_id );
if( empty($parent_id) ) return [];
$query = "SELECT ID FROM {$wpdb->posts} P WHERE post_type='attachment' AND P.post_parent IN (SELECT ID FROM {$wpdb->posts} WHERE post_parent={$parent_id} AND post_type='page' )";
return $wpdb->get_results($query, 'ARRAY_A');
}
Once you have above function in your functions.php, then you can use it like this:
// for example the parent page id is 16
$image_ids = get_children_page_attachments(16);
foreach($image_ids as $image_id) {
$image = wp_get_attachment_image($image_id['ID'], 'full');
}

wp returns "wrong" image ID

well,
Code dosent make mistakes so i have something i dont see here...
I have following code on wp page:
$args = array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'post_parent' => $pages->ID
);
$images = get_posts($args);
$attachment_id = $images[0]->ID;
$i = wp_get_attachment_image_src($attachment_id, $size);
$p = array_values($i)[0];
if (has_post_thumbnail()) {
the_post_thumbnail($size);
} else {
} ?>
It, works, in a way.
it will return a image url and i can use it to show images on page, anyhow the ID it return seems to be somewhat random.
I have the right ID for page to look for images in $pages
i would need to return first image of that page.
I would assume, array[0] would be first image of page, but obviously it is not since it returns very strange pictures from another page, which has nothing to do with this page.
I'm not sure but seems you are doing it wrong. :)
Why can't you use
echo get_the_post_thumbnail( $post_id, 'thumbnail', array( 'class' => 'alignleft' ) )
or
get_the_post_thumbnail_url( int|WP_Post $post = null, string|array $size = 'post-thumbnail' )
or
get_post_thumbnail_id( $post_id );
Please Try :
global $post;
$args = array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'post_parent' => $pages->ID
);
$images = get_posts($args);
$attachment_id = $images[0]->ID;
$i = wp_get_attachment_image_src($attachment_id, $size);
$p = array_values($i)[0];
if (has_post_thumbnail($post->ID )) {
the_post_thumbnail($size);
} else {
}

How to get all attachments for a wordpress post?

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);

Remove width and height from gallery images in Wordpress

I am in the process of modifying a WP installation.
I am using a modified Gallery shortcode to display the galleries, and a filter to remove width and height parameters which is required in order to keep pages responsive.
My problem is that the galleries display properly when I link to an attachment page (the default). However when I link the thumbnail to a file the width and height parameters aren't removed by the filter.
This is the filter:
/** remove gallery height and width*/
add_image_size( 'my_gallery_shortcode', 200, 120, true );
add_filter('wp_get_attachment_link', 'remove_img_width_height', 10, 4);
function remove_img_width_height( $html, $post_id, $post_image_id, $post_thumbnail) {
if ($post_thumbnail=='my_gallery_shortcode'){
$html = preg_replace( '/(width|height)=\"\d*\"\s/', "", $html );
}
return $html;
}
/** END remove gallery height and width*/
This is the custom gallery code:
/** custom gallery code */
add_shortcode('gallery', 'my_gallery_shortcode');
function my_gallery_shortcode($attr) {
$post = get_post();
static $instance = 0;
$instance++;
if ( ! empty( $attr['ids'] ) ) {
// 'ids' is explicitly ordered, unless you specify otherwise.
if ( empty( $attr['orderby'] ) )
$attr['orderby'] = 'post__in';
$attr['include'] = $attr['ids'];
}
// Allow plugins/themes to override the default gallery template.
$output = apply_filters('post_gallery', '', $attr);
if ( $output != '' )
return $output;
// We're trusting author input, so let's at least make sure it looks like a valid orderby statement
if ( isset( $attr['orderby'] ) ) {
$attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );
if ( !$attr['orderby'] )
unset( $attr['orderby'] );
}
extract(shortcode_atts(array(
'order' => 'ASC',
'orderby' => 'menu_order ID',
'id' => $post->ID,
'itemtag' => 'dl',
'icontag' => 'dt',
'captiontag' => 'dd',
'columns' => 3,
'size' => 'medium',
'include' => '',
'exclude' => ''
), $attr));
$id = intval($id);
if ( 'RAND' == $order )
$orderby = 'none';
if ( !empty($include) ) {
$_attachments = get_posts( array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
$attachments = array();
foreach ( $_attachments as $key => $val ) {
$attachments[$val->ID] = $_attachments[$key];
}
} elseif ( !empty($exclude) ) {
$attachments = get_children( array('post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
} else {
$attachments = get_children( array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
}
if ( empty($attachments) )
return '';
if ( is_feed() ) {
$output = "\n";
foreach ( $attachments as $att_id => $attachment )
$output .= wp_get_attachment_link($att_id, $size, true) . "\n";
return $output;
}
$itemtag = tag_escape($itemtag);
$captiontag = tag_escape($captiontag);
$icontag = tag_escape($icontag);
$valid_tags = wp_kses_allowed_html( 'post' );
if ( ! isset( $valid_tags[ $itemtag ] ) )
$itemtag = 'dl';
if ( ! isset( $valid_tags[ $captiontag ] ) )
$captiontag = 'dd';
if ( ! isset( $valid_tags[ $icontag ] ) )
$icontag = 'dt';
$columns = intval($columns);
$itemwidth = $columns > 0 ? floor(100/$columns) : 100;
$float = is_rtl() ? 'right' : 'left';
$selector = "gallery-{$instance}";
$gallery_style = $gallery_div = '';
$size_class = sanitize_html_class( $size );
$gallery_div = "<div id='$selector' class='gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class}'>";
$output = apply_filters( 'gallery_style', $gallery_style . "\n\t\t" . $gallery_div );
$i = 0;
foreach ( $attachments as $id => $attachment ) {
$link = isset($attr['link']) && 'file' == $attr['link'] ? wp_get_attachment_link($id, $size, false, false) : wp_get_attachment_link($id, $size, true, false);
$output .= "<{$itemtag} class='gallery-item'>";
$output .= "
<{$icontag} class='gallery-icon'>
$link
</{$icontag}>";
if ( $captiontag && trim($attachment->post_excerpt) ) {
$output .= "
<{$captiontag} class='wp-caption-text gallery-caption'>
" . wptexturize($attachment->post_excerpt) . "
</{$captiontag}>";
}
$output .= "</{$itemtag}>";
}
$output .= "
</div>\n";
return $output;
}
Can anyone help ensure that gallery thumbnail images, in all sizes, are displayed without dimensions regardless of what they link to?
To make a responsive gallery you really dont need to remove all the height and weight tag from the IMG. All you need to do is add some css to you image tag.
For example:
<div class="facebook">
<img src="http:///" height="100" width="100" >
To make this image responsive add this css
div.facebook img
{
width: 100%;
}
If you have the Problem when you add a Image with the Gutenberg Blog Editor use this css in your css file to set the width and height auto so there is no problem anymore:
figure > img {
width: auto;
height: auto;}
:-)

How to extract images of post and pages excluding header and logo image in wordpress?

I have tried this code to get all images from media library and i am sucessfully getting the source urls of all the images but now i want to exclude all the unwanted images like logo, header images ,etc ...
In short i want to extract all images attached to posts and pages ..
if(is_single() || is_page() || is_home() ){
global $post;
$query_images_args = array(
'post_type' => 'attachment', 'post_mime_type' =>'image', 'post_status' => 'inherit', 'posts_per_page' => -1,'numberposts' => 1
);
$query_images = new WP_Query( $query_images_args );
$images = array();
foreach ( $query_images->posts as $image) {
$images[]= wp_get_attachment_url( $image->ID );
}
echo "<pre>";
print_r($images);
echo "</pre>";
My output
Here the first image is a header image which is unwanted for me ..How to exclude it ..I have tried using attachment size but it cant be unique all the time .. Have a look at it
Array
(
[0] => http://localhost/wordpress/wp-content/uploads/2013/03/AboutUsSlider.jpg
[1] => http://localhost/wordpress/wp-content/uploads/2013/03/7325996116_9995f40082_n.jpg
[2] => http://localhost/wordpress/wp-content/uploads/2013/03/6310273151_31b2d7bebe.jpg
[3] => http://localhost/wordpress/wp-content/uploads/2013/03/4764924205_ce7470f15a.jpg
[4] => http://localhost/wordpress/wp-content/uploads/2013/03/2166105529_70dd50ef4b_n.jpg
[5] => http://localhost/wordpress/wp-content/uploads/2013/03/1494822863_aca097ada7.jpg
[6] => http://localhost/wordpress/wp-content/uploads/2013/03/1385429771_453bc19702.jpg
)
From this point you may want to specify what you would like to filter.
$images[]= wp_get_attachment_url( $image->ID );
}
$linkstoremove[] = $linksyouwanttoremove;
//remove unwanted images
$filtered_images = array_filter($images, $linkstoremove);
//set data sequence
$filtered_images = array_values($filtered_images);
print_r($filtered_images);
Query the db and fetch the posts, then apply any filters and extract from each post and/or image all the images that are within those posts. For example:
$my_images = array();
$query_images_args = array(
'post_type' => 'attachment', 'post_mime_type' =>'image', 'post_status' => 'inherit', 'posts_per_page' => -1,'numberposts' => 1
);
$query_images = new WP_Query( $query_images_args );
while ( $query_images->have_posts() ) : $query_images->the_post();
$dcontent = apply_filters('the_content', get_the_content());
$dcontent = preg_replace("/\< *[img][^\>]*[.]*\>/i","",$dcontent,1);
if ( preg_match_all('/<img (.+?)>/', $dcontent, $matches) ) {
foreach ($matches[1] as $match) {
foreach ( wp_kses_hair($match, array('http')) as $attr)
$img[$attr['name']] = $attr['value'];
$my_images[] = $img['src'];
}
}
endwhile;
Not 100% efficient but it works.

Categories