Hello all, I'm currently working on a foreach loop that pulls images from a gallery from the backend of Wordpress. The gallery is working fine and as expected, however, I would like to prevent duplicate photos from appearing.
<?php if () $query->have_posts() ):
$thumbs = [];
?>
<?php
foreach( $query->posts as $gallery ):
$images = get_field('gallery_images', $gallery->ID);
if( $images ):
foreach( $images as $image ):
$cropped_img = aq_resize( $image['url'], 1024, 576, true, true, true );
$img_id[] = $image['ID'];
$thumbs[] = $cropped_img;
?>
Unrelated HTML to the Problem
<?php endforeach; endif; endforeach; ?>
<?php foreach($thumbs as $thumbnail): ?>
<div class="gallery__thumb"><img src="<?= $thumbnail; ?>"></div>
<?php endforeach; ?>
Here is essentially what I'm trying to work out. I've thought to add two variables for the image ID so that they aren't duplicated in the first block of code. So that first if/foreach state looks like:
<?php if( $images ):
foreach( $images as $image ):
$cropped_img = aq_resize( $image['url'], 1024, 576, true, true, true );
$img_id[] = $image['ID'];
$do_not_duplicate[] = $image['ID'];
$thumbs[] = $cropped_img;
?>
Followed by the followed foreach for the thumbnails
<?php foreach($thumbs as $thumbnail): ?>
<?php foreach($img_id as $img): ?>
<?php if ($img == $do_not_duplicate) : ?>
//do nothing
<?php else : ?>
<div class="gallery__thumb"><img src="<?= $thumbnail; ?>"></div>
<?php endif; ?>
<?php endforeach; endforeach; ?>
The problem I'm experiencing with this is I'm getting 22 images outputed 23 times because there are 22 images being pulled(with 1 duplicate). Essentially I'm trying to accomplish 22 images with no duplicates.
Any insight would be greatly appreciated, thank you in advance.
Simply edit your php code like that:
$thumbs[$image['ID']] = $cropped_img;
It will be an associative array in which the images are stored with ids as keys, so if an doubled image is pushed to array, it will just override the old one
Based on your code, it should be:
<?php if( $images ):
foreach( $images as $image ):
$cropped_img = aq_resize( $image['url'], 1024, 576, true, true, true );
$img_id[] = $image['ID'];
$thumbs['url'][] = $cropped_img;
$thumbs['id'][] = $image['ID']
?>
then
<?php foreach($thumbs as $thumbnail): ?>
<?php if (!in_array($thumbnail['do_not_duplicate'], $img_id)): ?>
<div class="gallery__thumb"><img src="<?= $thumbnail['url']; ?>"></div>
<?php endif; ?>
<?php endforeach; ?>
You could check if the image id already exists in the $img_id array before adding it.
I modified your code below
<?php if () $query->have_posts() ):
$thumbs = [];
?>
<?php
foreach( $query->posts as $gallery ):
$images = get_field('gallery_images', $gallery->ID);
if( $images ):
// Initialize $img_id[]
$img_id = [];
foreach( $images as $image ):
// Only add to the $img_id array and $thumbs array if
// $image['ID'] is not in $img_id array
if( ! in_array($image['ID'], $img_id)):
$cropped_img = aq_resize( $image['url'], 1024, 576, true, true, true );
$img_id[] = $image['ID'];
$thumbs[] = $cropped_img;
?>
Hope this helps!
Depending on what your $image['ID'] values are, you may need to pass use the third argument of in_array() to do strict checking.
Reference: http://php.net/manual/en/function.in-array.php
Related
Hi i'm use plugin DCO Comment Attachment to be able to add images to comments, I use code below get list comments. Now I want to get the image link of the comment to handle before showing it to the screen. Currently according to the code below, it only takes all the image files attached to the comment post, not each comment.
I tried instead $comment->comment_post_ID to $comment->comment_ID but it does not work.
Thank everyone!
<?php $comments = get_comments($param);?>
<?php foreach ($comments as $comment): ?>
<?php if ($comment->comment_approved != '0'): ?>
<?php
$attachments = get_posts(array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => 'any',
'post_parent' => $comment->comment_post_ID,
));
if ($attachments) {
foreach ($attachments as $attachment) {
echo wp_get_attachment_url($attachment->ID);
}
}
?>
<?php endif;?>
<?php endforeach;?>
After self-study, I know how to get the url image in the comment with the following code, this code put in the functions.php file.
function get_attachment_url_image_comment($comment_id) {
$meta_key = 'attachment_id';
$attachment_id = get_comment_meta( $comment_id, $meta_key, true );
$full_img_url = wp_get_attachment_image_url( $attachment_id, 'full' );
return $full_img_url;
}
All that's left to do is pass the desired comment ID into the function and get the attached image
<?php $comments = get_comments($param);?>
<?php foreach ($comments as $comment): ?>
<?php if ($comment->comment_approved != '0'): ?>
<?php if(get_attachment_url_image_comment($comment->comment_ID)): ?>
<?php echo get_attachment_url_image_comment($comment->comment_ID) ?>
<?php endif; ?>
<?php endif;?>
<?php endforeach;?>
Result: "http://localhost/wp-content/uploads/2020/07/11439468-3x4-xlarge-2.jpg"
It works fine!
I have a custom field called "images". I would like to show this custom field as a picture. How can I do that?
https://prnt.sc/l0eyv3
I've written a php code, but it shows only 1 image, it doesn't show any other images.
my code:
<?php $images = get_post_meta(get_the_ID(), 'images', true); ?>
<?php if ( $images && is_single() ): ?>
<?php
$images = get_post_meta( $post->ID, 'images' );
if ( $images ) {
foreach ( $images as $attachment_id ) {
$thumb = wp_get_attachment_image( $attachment_id, 'full' );
$full_size = wp_get_attachment_url($attachment_id);
printf( '%s', $full_size, $thumb );
}
}
?></br>
<?php endif; ?>
This should work. See comment for explanation.
<?php
$images = get_post_meta(get_the_ID(), 'images', true);
if ( $images && is_single() ):
$images = get_post_meta( $post->ID, 'images' );
if ( $images ) {
//you can't loop through strings, you need to convert the string to an array
$images = explode( ",", $images );
foreach ( $images as $attachment_id ) {
$thumb = wp_get_attachment_image( intval($attachment_id), 'full' );
$full_size = wp_get_attachment_url($attachment_id);
printf( '%s', $full_size, $thumb );
}
}
echo '<br>';
endif;
?>
I am using Meta Box Plugin
I have two options in Post Edit. One to add a Logo and one to add a Title. On the front end (in my template) I want to show either the Logo or the Title, but not both.
I added this code to my template however it is not working:
<?php if( rwmb_meta('restauranttheme_hero_small_logo', false, 'url') !== '' ) { ?>
<?php $images = rwmb_meta( 'restauranttheme_hero_small_logo', 'type=image_advanced&size=full' );
foreach ( $images as $image ) {
echo "<img src='{$image['url']}'>"; } ?>
<?php } else { ?>
<h1 class="mini-title"><?php echo rwmb_meta('restauranttheme_hero_title' ); ?></h1>
<?php } ?>
I also tried:
<?php if( '' != rwmb_meta('restauranttheme_hero_small_logo' ) ) { ?>
<?php $images = rwmb_meta( 'restauranttheme_hero_small_logo', 'type=image_advanced&size=full' );
foreach ( $images as $image ) {
echo "<img src='{$image['url']}'>"; } ?>
<?php } else { ?>
<h1 class="mini-logo"><?php echo rwmb_meta('restauranttheme_hero_title' ); ?></h1>
<?php } ?>
I guess the error is in my if else statement.
Can anyone help?
Thanks so much
This could be a duplicate question, but not one of these similiar questions has touched the get_attached_media part, which is what I need help with.
If I don't have any Featured Image in the post, I want to use the image attached in the content of the post, as a Featured Image.
Here is what I'm trying and failing:
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php
if(get_post_thumbnail_id() == TRUE) {
$image_url = wp_get_attachment_image_src( get_post_thumbnail_id(), 'backstretch' );
}
else {
$image_url = wp_get_attachment_image_src( get_attached_media('image'), 'backstretch');
}
?>
<header class="backstretch-target backstretch-header <?php echo crisp_filter_img() ?>" data-background="<?php echo $image_url[0]; ?>">
I've realised I need to fetch the url of get_attached_media('image') for it to work. But even with using foreach I've not managed this:
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php
function get_image($arr) {
$images = get_attached_media('image');
$arr = [];
foreach($images as $image) {
$url = wp_get_attachment_url($image->ID);
$image_url = wp_get_attachment_image_src($url, 'backstretch');
$arr[] = $image_url;
}
return $arr;
}
?>
<header class="backstretch-target backstretch-header <?php echo crisp_filter_img() ?>" data-background="<?php echo get_image($arr[0]); ?>">
My url becomes this:
http://site.loc/wp/2016/01/05/postname/%3Cbr%20/%3E%3Cfont%20size='1'%3E%3Ctable%20class='xdebug-error%20xe-notice'%20dir='ltr'%20border='1'%20cellspacing='0'%20cellpadding='1'%3E%3Ctr%3E%3Cth%20align='left'%20bgcolor='
Which clearly states that it gets image attributes as url. I've googled and played with the code, and I just can't find realize the problem.
I really appreciate your help.
Also if you still find this as a duplicate, I apologize!
I use this function to get all available images from a WordPress post:
function get_post_images( $post = null ) {
if ( $post === null ) {
global $post;
}
/* Get the featured image of the post */
if ( has_post_thumbnail() ) {
$images[] = get_post_thumbnail_id( $post->ID );
}
/* If the post contains galleries, get all images from them */
if( has_shortcode( $post->post_content, 'gallery' ) ) {
$galleries = get_post_galleries( $post, false );
foreach ( $galleries as $gallery ) {
$ids = explode( ',', $gallery['ids'] );
$images = array_merge( $images, $ids );
}
}
/* Get all single images in the post */
preg_match_all("/wp-image-(\d+)/", $post->post_content, $imgs );
foreach ($imgs[1] as $img) {
$images[] = $img;
}
/* get all images attached to the post
* not sure if this is a good idea, there might be images attached
* which were not supposed to be published */
$post_images = get_posts( array(
'post_parent' => $post->ID,
'post_type' => 'attachment',
'numberposts' => -1,
'post_mime_type' => 'image',
'exclude' => $images ) );
foreach ( $post_images as $image ) {
$images[] = $image->ID;
}
/* As a fallback, add a predefined default image */
if ( sizeof( $images ) == 0 && $this->default_image != null) {
$images[] = $this->default_image;
}
/* remove duplicated images */
$images = array_unique( $images );
return $images;
}
The function returns an array containing all image IDs related to the given post, if you only need one you can extract that easily:
$images = get_post_images();
echo wp_get_attachment_image( array_shift( $images ) );
Well, I fixed the problem. I tried to use the popular get_that_image plugin, but it didn't fix my problem. At the end of the day I trashed the get_attached_media, and used this function which I found here.
function crisp_catch_that_image() {
$image_url = wp_get_attachment_image_src( get_post_thumbnail_id(), 'backstretch' );
if (!empty($image_url)) {
return $image_url[0];
}
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
if (empty($matches[1])) {
return '';
}
return $matches[1][0];
return $first_img;
}
I have this code in displaying content, it use "while" loop
<?php
$mypost = array( 'post_type' => 'testimonials', );
$loop = new WP_Query( $mypost );
while ( $loop->have_posts() ) : $loop->the_post();$do_not_duplicate = $post->ID;
$image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' );
echo "{image : '$image[0];'},";
endwhile;
?>
But what I want to achieve is, to remove the comma of the last loop so for example I have a 3 stuff to loop then the scenario should be like this.
{image : 'http://website.com/wp-content/uploads/2013/09/image1.jpg'},
{image : 'http://website.com/wp-content/uploads/2013/09/image2.jpg'},
{image : 'http://website.com/wp-content/uploads/2013/09/image3.jpg'}
as you can see at the third loop the comma was removed, that's what I am trying to achieve. But so far I have no idea how to make that.
I am open in any suggestion, recommendation and ideas.
$images = array();
while ( $loop->have_posts() ) : $loop->the_post();$do_not_duplicate = $post->ID;
$images[] = "{image : '<?php echo get_option('slider3_Field');?>'}";
endwhile;
echo implode(',', $images);
You want to use it as JSON, right? Why not separate your PHP from your JS?
$images = array();
while ( $loop->have_posts() ) : $loop->the_post(); $do_not_duplicate = $post->ID;
$images[] = (object) array('image' => wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' )[0]);
endwhile;
echo json_encode($images);
instead of echo have your tried savins as a variable i.e.
while ( $loop->have_posts() ) : $loop->the_post();$do_not_duplicate = $post->ID;
$str .= "{image : '<?php echo get_option('slider3_Field');?>'},";
endwhile;
rtrim($str,',');
echo $str;