using wp_get_attachment_image_src in foreach loop - wordpress

I have 10 images added to a post via Advanced Custom Fields, they're named from 1 to 10 e.g 'image_*', ACF is set to return the ID.
I'm trying to get the full size image URL of each image in the loop and use it as a href attribute to open a full size popup of the image, however I don't understand how wp_get_attachment_image_src works.
Since I am unable to use Advanced Custom Field's Repeater, this is the loop i'm using to get an array of the images with a custom image size of scaled, it works fine to generate the responsive image markup that I need:
// args
$sizeHuge = 'scaled'; // scaled image
$images = array(); // img array
for($x = 1; $x <= 10; $x++) {
$img = get_field('image_' . $x);
if($img) {
$images[] = $img;
} else {
break;
}
}
<?php foreach($images as $image) { ?>
<a href="" class="open-viewer">
<?php echo wp_get_attachment_image( $image, $sizeHuge ); ?>
</a>
<?php } ?>
I need to set the href attribute of the parent a element with the URL of the image. This is what I have tried with wp_get_attachment_image_src, it doesn't work, it sets every href with image_10's URL.
// args
$sizeFull = 'full'; // full size image
$sizeHuge = 'scaled'; // scaled image
$images = array(); // img array
for($x = 1; $x <= 10; $x++) {
$img = get_field('image_' . $x);
$image_array = wp_get_attachment_image_src($img, $sizeFull);
$link = $image_array[0];
if($img) {
$images[] = $img;
} else {
break;
}
}
<?php foreach($images as $image) { ?>
<a href="<?php echo $link; ?>" class="open-viewer">
<?php echo wp_get_attachment_image( $image, $sizeHuge ); ?>
</a>
<?php } ?>
My question is: How can I set the href of a.open-viewer with the correct URL?, and secondly, why does my code fail? (debug is switched on but no errors appear).
I realise I've horribly misunderstood something here, I'm a PHP novice so any advice about my approach would be appreciated.

In your first block, in your loop, you're setting the value of $link to the value of $image_array[0], but you're overwriting it each time. You want array_push here.
$images = array();
for($x = 1; $x <= 10; $x++) {
$img = get_field('image_' . $x);
$image_array = wp_get_attachment_image_src($img, $sizeFull);
if($image_array && $image_array[0]) {
array_push($images,
array(
src => $image_array[0],
id => $img
)
);
} else {
break;
}
}
Now, when you loop over it the second array, you can just do:
<?php foreach($images as $image) { ?>
<a href="<?php echo $image['src']; ?>" class="open-viewer">
<?php echo wp_get_attachment_image( $image['id'], $sizeHuge ); ?>
</a>
<?php } ?>
And the value of href should be the image URL.

Following is the updated/corrected code which will work for you:
<?php
// args
$sizeFull = 'full'; // full size image
$sizeHuge = 'scaled'; // scaled image
$images = array(); // img array
for($x = 1; $x <= 10; $x++) {
$img = get_field('image_' . $x);
if($img) {
$images[] = $img;
} else {
break;
}
}
<?php foreach($images as $image) {
$image_array = wp_get_attachment_image_src($image, $sizeFull);
$link = $image_array[0];
?>
<a href="<?php echo $link; ?>" class="open-viewer">
<?php echo wp_get_attachment_image( $image, $sizeHuge ); ?>
// or Rather than calling above function, why don't you write <img> tag as you already have image url ? Like:
<img src="<?php echo $link; ?>" class="">
</a>
<?php } ?>

Related

Different Styling for Last Thumbnail in Advance Custom Fields Pro Gallery

I've created an image gallery using Advance Custom Fields pro with lighbox and limited it to show only 4 thumbnails, and that's working perfectly. When someone click on any thumbnail, the gallery opens up in lightbox and shows all the images in it.
Now I want to use different css styling for the 4th thumbnail but don't know how to do that.
Here's my code:
<?php
$images = get_field('menu_gallery');
$image_1 = $images[0];
if( $images ) { ?>
<ul class="gal-grid">
<?php
$i = 0;
foreach( $images as $image ) {
if ($i >= 5) {
$content = '<li class="gal-grid-zom">';
$content = '<a class="gallery_image" href="'. $image['url'] .'"></a>';
$content .= '</li>';
} else {
$content = '<li class="gal-grid">';
$content = '<li class="gal-grid"><a class="gallery_image" href="'. $image['url'] .'">';
$content .= '<img class="gallery-zom" src="'. $image['sizes']['thumbnail'] .'" alt="'. $image['alt'] .'" />';
$content .= '</a>';
$i++;
}
$content .= '</li>';
if ( function_exists('slb_activate') ) {
$content = slb_activate($content);
}
echo $content;
?>
<?php } ?>
<?php } ?> </ul>
Can someone help me regarding this issue?
You can add the $key inside your foreach loop :
foreach( $images as $key => $image ) {
if( $key === 3 ) {
// it will show the specific <li> for the 4th iteration.
<li class="fourth-grid">The Image</li>
} else {
<li class="gal-grid">The image</li>
}
}

Woocommerce Custom shop page with infinte load

Hi currently I am creating a woocommerce custom shop page template .
For this, I have created a new template inside my theme page called custom-shop & I have created new page called my shop and assign custom-shop template.
I have 3 main category called car , bus, boat . Now I am going to display each category with its description and product details
So I write the following code in my cutom-shop template(custom-shop.php)
custom-shop.php
/*
Template name: custom-shop
*/
BLOCKS OF CODE
<div class="category-block">
<h2>Car</h2>
<p class="description">Car Description</p>
<?php echo do_shortcode('[products limit="40" columns="4" category="car"]'); ?>
</div>
<div class="category-block">
<h2>Bus</h2>
<p class="description">Bus Description</p>
<?php echo do_shortcode('[products limit="40" columns="4" category="bus"]'); ?>
</div>
<div class="category-block">
<h2>Boat</h2>
<p class="description">Boat Description</p>
<?php echo do_shortcode('[products limit="40" columns="4" category="boat"]'); ?>
</div>
Here Everything is working fine . But the problem is the page load time is high , because every product is loading together . How can i solve this issue , how can i implement infinite load ?
What I need is first display car and it's 4 products then user scroll down display other products in car . After car products finished then display bus and it's 4 products , like this
what I tried is
After searching I found a plugin https://wordpress.org/plugins/ajax-load-more/ and i t help to resolve some issue and i used this plugin code
<div class="category-block">
<h2>Car</h2>
<p class="description">Car Description</p>
<?php do_shortcode('[ajax_load_more post_type="product" columns="4" css_classes="products" posts_per_page="4" transition="fade" taxonomy="product_cat" taxonomy_terms="car" taxonomy_operator="IN" button_label=""]'); ?>
</div>
<div class="category-block">
<h2>Bus</h2>
<p class="description">Bus Description</p>
<?php do_shortcode('[ajax_load_more post_type="product" columns="4" css_classes="products" posts_per_page="4" transition="fade" taxonomy="product_cat" taxonomy_terms="car" taxonomy_operator="IN" button_label=""]'); ?>
</div>
<div class="category-block">
<h2>Car</h2>
<p class="description">Boat Description</p>
<?php do_shortcode('[ajax_load_more post_type="product" columns="4" css_classes="products" posts_per_page="4" transition="fade" taxonomy="product_cat" taxonomy_terms="car" taxonomy_operator="IN" button_label=""]'); ?>
</div>
But here the problem is that when I scroll down it will first show car and it's 4 products , then bus and it's 4 products again load other products for car . So it's not also proper solution .
Please help , to solve this issue .
actually if you want to do it by yourself, I will just suggest you to follow this guide, cmmon click me! -> It will be lots more helpful than any huge reply in here.
This guy goes trough all the ajax proceses that you will need to use. Also you can just parse a piece of his code and get it all done. Shortly, you just need ajax. more explicit -> you can see in this video
I will paste in here the code result of the guide bypassing all the small procedures for a better understanding
First of all he created a template to output the content wich looks like this
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<header class="entry-header text-center">
<?php the_title( '<h1 class="entry-title">', '</h1>'); ?>
<div class="entry-meta">
<?php echo sunset_posted_meta(); ?>
</div>
</header>
<div class="entry-content">
<?php if( sunset_get_attachment() ): ?>
<a class="standard-featured-link" href="<?php the_permalink(); ?>">
<div class="standard-featured background-image" style="background-image: url(<?php echo sunset_get_attachment(); ?>);"></div>
</a>
<?php endif; ?>
<div class="entry-excerpt">
<?php the_excerpt(); ?>
</div>
<div class="button-container text-center">
<?php _e( 'Read More' ); ?>
</div>
</div><!-- .entry-content -->
<footer class="entry-footer">
<?php echo sunset_posted_footer(); ?>
</footer>
</article>
Next step was to validate in wp the ajax function
add_action( 'wp_ajax_nopriv_sunset_load_more', 'sunset_load_more' );
add_action( 'wp_ajax_sunset_load_more', 'sunset_load_more' );
function sunset_load_more() {
$paged = $_POST["page"]+1;
$prev = $_POST["prev"];
$archive = $_POST["archive"];
if( $prev == 1 && $_POST["page"] != 1 ){
$paged = $_POST["page"]-1;
}
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'paged' => $paged
);
if( $archive != '0' ){
$archVal = explode( '/', $archive );
$type = ( $archVal[1] == "category" ? "category_name" : $archVal[1] );
$args[ $type ] = $archVal[2];
$page_trail = '/' . $archVal[1] . '/' . $archVal[2] . '/';
} else {
$page_trail = '/';
}
$query = new WP_Query( $args );
if( $query->have_posts() ):
echo '<div class="page-limit" data-page="' . $page_trail . 'page/' . $paged . '">';
while( $query->have_posts() ): $query->the_post();
get_template_part( 'template-parts/content', get_post_format() );
endwhile;
echo '</div>';
else:
echo 0;
endif;
wp_reset_postdata();
die();
}
function sunset_check_paged( $num = null ){
$output = '';
if( is_paged() ){ $output = 'page/' . get_query_var( 'paged' ); }
if( $num == 1 ){
$paged = ( get_query_var( 'paged' ) == 0 ? 1 : get_query_var( 'paged' ) );
return $paged;
} else {
return $output;
}
}
And the last step will be the AJAX function itself.
/* Ajax functions */
$(document).on('click','.sunset-load-more:not(.loading)', function(){
var that = $(this);
var page = $(this).data('page');
var newPage = page+1;
var ajaxurl = that.data('url');
var prev = that.data('prev');
var archive = that.data('archive');
if( typeof prev === 'undefined' ){
prev = 0;
}
if( typeof archive === 'undefined' ){
archive = 0;
}
that.addClass('loading').find('.text').slideUp(320);
that.find('.sunset-icon').addClass('spin');
$.ajax({
url : ajaxurl,
type : 'post',
data : {
page : page,
prev : prev,
archive : archive,
action: 'sunset_load_more'
},
error : function( response ){
console.log(response);
},
success : function( response ){
if( response == 0 ){
$('.sunset-posts-container').append( '<div class="text-center"><h3>You reached the end of the line!</h3><p>No more posts to load.</p></div>' );
that.slideUp(320);
} else {
setTimeout(function(){
if( prev == 1 ){
$('.sunset-posts-container').prepend( response );
newPage = page-1;
} else {
$('.sunset-posts-container').append( response );
}
if( newPage == 1 ){
that.slideUp(320);
} else {
that.data('page', newPage);
that.removeClass('loading').find('.text').slideDown(320);
that.find('.sunset-icon').removeClass('spin');
}
revealPosts();
}, 1000);
}
}
});
});
/* scroll function */
$(window).scroll( function(){
var scroll = $(window).scrollTop();
if( Math.abs( scroll - last_scroll ) > $(window).height()*0.1 ) {
last_scroll = scroll;
$('.page-limit').each(function( index ){
if( isVisible( $(this) ) ){
history.replaceState( null, null, $(this).attr("data-page") );
return(false);
}
});
}
});
/* helper functions */
function revealPosts(){
var posts = $('article:not(.reveal)');
var i = 0;
setInterval(function(){
if( i >= posts.length ) return false;
var el = posts[i];
$(el).addClass('reveal').find('.sunset-carousel-thumb').carousel();
i++
}, 200);
}
function isVisible( element ){
var scroll_pos = $(window).scrollTop();
var window_height = $(window).height();
var el_top = $(element).offset().top;
var el_height = $(element).height();
var el_bottom = el_top + el_height;
return ( ( el_bottom - el_height*0.25 > scroll_pos ) && ( el_top < ( scroll_pos+0.5*window_height ) ) );
}
});
I would suggest you to follow the guide created by alecadd because it will be much easier to understand the process and suit it for your purposes. Hope it's enough now!
Cheers.

Get thumbnail from page? (Concrete 5.7.4.2)

As posted here https://www.concrete5.org/index.php?cID=751287 I want to get a thumbnail from a page using the 'old' way.
Before I could use the code below which included an image helper.
<div class="image-link">
<a <?php if ($target != '') { ?> target="<?php echo $target ?>" <?php } ?> href="<?php echo $url ?>">
<?php
$ts = $page->getBlocks('Thumbnail Image');
if (is_object($ts[0])) {
$tsb = $ts[0]->getInstance();
$thumb = $tsb->getFileObject();
if ($thumb) {
$ih->outputThumbnail($thumb, 170, 80, $title);
}
}
?>
</a>
</div>
From this section of the subpage:
<div id="thumbnail">
<?php
if ($c->isEditMode()) {
print '<br><br>';
$a = new Area('Thumbnail Image');
$a->display($c);
}
?>
</div>
However now this has all changed and the new system uses page attributes for thumbnails. As the site is already setup the 'old' way I want to be able to retrieve the thumbnail the same way again.
Any help would be much appreciated.
I have "thumbnail" page attribute set via the composer, and this is how I retrieve it in the page template:
<?php
$thumbnail = $c->getAttribute('thumbnail');
if($thumbnail) {
$img = Core::make('html/image', array($thumbnail));
$tag = $img->getTag();
print $tag;
}
?>
I dug out my experimentation hat and fixed it.
<div class="image-link">
<a <?php if ($target != '') { ?> target="<?php echo $target ?>" <?php } ?> href="<?php echo $url ?>">
<?php
foreach ($blocks as $block) {
if ($block->getBlockTypeHandle() == "image" && $block->getAreaHandle() == "Thumbnail Image") {
if (is_object($block)) {
$tsb = $block->getInstance();
$thumb = $tsb->getFileObject();
if ($thumb) {
$ih->outputThumbnail($thumb, 170, 80);
}
}
}
}
?>
</a>
</div>

Wordpress getFeaturedImage

I have a real-estate website in wordpress.
Under each listed property is displayed a corresponding agent. Everything works fine, but the problem is that i want that agent's featured image to be displayed as well.
Here is the code for displaying the agent under each property
<?php
//// CHECKS TO SEE IF WE HAVE ANY GENTS ASSIGNED TO THIS PROPERTY
if(get_post_meta(get_the_ID(), 'agents', true) != '' || ddp('public_submissions') == 'on') :
?>
<div id="property-agents">
<h2><?php _e('Contact Agent', 'btoa'); ?></h2>
<ul class="list-agents">
<?php
//// LETS LOOP OUR AGENTS
$agents = get_post_meta(get_the_ID(), 'agents', true);
//// IF WE HAVE AN ARRAY
if(is_array($agents)) :
foreach($agents as $agent) :
$this_agent = '';
//// IF IT'S A POST TYPE
if($this_agent = get_post($agent)) {
if($this_agent->post_type == 'agent') {
$name = $this_agent->post_title;
$position = get_post_meta($this_agent->ID, 'position', true);
$email = get_post_meta($this_agent->ID, 'email', true);
$phone = get_post_meta($this_agent->ID, 'phone', true);
} else { $this_agent = 'user'; }
} else { $this_agent = 'user'; }
if($this_agent == '' || $this_agent == 'user') {
if($this_agent = get_user_by('id', $agent)) {
$name = $this_agent->display_name;
$position = esc_attr( get_the_author_meta( 'position', $this_agent->ID ) );
$email = $this_agent->user_email;
$phone = get_the_author_meta( 'phone', $this_agent->ID );
}
}
//// IF WE HAVE GOTTEN THE USERS NAME
if($name) :
?>
<li>
<div class="two-fifths">
<h4><?php echo $name; ?></h4>
<h5><?php echo $position; ?></h5>
</div>
<!-- /.two-fifths/ -->
<div class="three-fifths last">
<?php if($email != '') : ?><div class="three-fifths"><strong><?php _e('Email', 'btoa'); ?></strong><?php echo $email; ?></div><?php endif; ?>
<?php if($phone != '') : ?><div class="two-fifths last"><strong><?php _e('Phone', 'btoa'); ?></strong><?php echo $phone; ?></div><?php endif; ?>
</div>
<!-- /.three-fifths/ -->
</li>
<?php endif; endforeach; endif; ?>
</ul>
</div>
<!-- /#property-agents/ -->
and this is the code for gettin the featured image
function ddTimthumb($img = NULL, $width = NULL, $height = NULL) {
//// IF AN imAGE HAS BEEN PROVIDED
if($img != NULL) {
$image = vt_resize('', $img, $width, $height, true );
//// IF ITS NOT AN ERROR
if(is_array($image)) { return $image['url']; } else { return ''; }
} else { return ''; }
}
function getFeaturedImage($post_id = NULL) {
if($post_id != NULL) {
$image = wp_get_attachment_image_src( get_post_thumbnail_id( $post_id ), 'single-post-thumbnail' );
return $image;
}
}
You can use your function to get featured image.
<?php echo getFeaturedImage($this_agent->ID); ?>

Categories and Sub Categories in custom taxonomies

I find and use the following code to display sub categories for default taxonomy 'category' on my site, but I created a custom taxonomy , and can not alter the code so that he was doing the same thing for the new taxonomy, help please
<?php
if(is_category()) {
$subcategories = get_terms('category', 'parent='.get_query_var('cat'));
if(empty($subcategories)) {
$thiscat = get_term(get_query_var('cat'),'category');
$subcategories = get_terms('category', 'parent='.$thiscat->parent.'');
}
if(empty($subcategories)) $subcategories = array();
if(!empty($subcategories)) {
echo '<ul>';
foreach($subcategories as $subcat) {
if(get_query_var('cat') == $subcat->term_id) $current = ' current-cat'; else $current = '';
echo '
<li class="cat-item cat-item-'.$subcat->term_id.$current.'">
'.$subcat->name.'
</li>';
}
echo '</ul>';
}
}
else {
// If no current cat query, just get the top level ones using wp_list_categories.
?>
<ul>
<?php wp_list_categories('title_li=&depth=1');?>
</ul>
<?php
}
?>
It turned out, the code works as I wanted, but if it can be optimize I'll be glad to help ... This code displays the subcategories to the main categories of taxonomies.
If anyone should use, just change 'auto' to the name of your taxonomy. my custom taxonomy is 'auto'
<?php
if(is_tax()) {
$subcategories = get_terms('auto', 'parent='.get_queried_object()->term_id);
if(empty($subcategories)) {
$thiscat = get_term(get_queried_object()->term_id,'auto');
$subcategories = get_terms('auto', 'parent='.$thiscat->parent.'');
}
if(empty($subcategories)) $subcategories = array();
if(!empty($subcategories)) {
echo '<ul>';
foreach($subcategories as $subcat) {
if(get_queried_object()->term_id == $subcat->term_id) $current = ' current-cat'; else $current = '';
echo '
<li class="cat-item cat-item-'.$subcat->term_id.$current.'">
'.$subcat->name.'
</li>';
}
echo '</ul>';
}
}
else {
// If no current cat query, just get the top level ones using wp_list_categories.
?>
<ul>
<?php wp_list_categories('taxonomy=auto&title_li=&depth=1');?>
</ul>
<?php
}
?>
Thanks for the corrected code.
I have added a bit for people who want to exit of the loop once they come to any end. Instead of showing the parent categories tree i modified a bit to display the image and title of the of the products or services under that specific category. Following is the code
if(is_tax()) {
$subcategories = get_terms('product_categories', 'parent='.get_queried_object()->term_id);
// this is the change which display all the products in the specific category if it does not have child categories
if(empty($subcategories)) {
$thiscat = get_term(get_queried_object()->term_id,'product_categories');
if (have_posts('thiscat')):while (have_posts('thiscat')) : the_post('thiscat');{?>
<div class="box cat-item-<?php $subcat->name.$current ;?>" style="min-height: 231px; margin-bottom:10px">
<?php the_post_thumbnail('thumbnail');?>
<h5><a title="<?php the_title(); ?>" href="<?php the_permalink($post->ID); ?>"><?php the_title(); ?></a></h5></h5></div>
<?php }
endwhile;
else : {
?>
<div class="box cat-item cat-item-<?php $subcat->name.$current; ?>" style="min-height: 231px; margin-bottom:10px">
<h5>Products will be upadated later. Do visit Later </h5 >
</div>
<?php }
endif;
}
if(empty($subcategories)) $subcategories = array();
if(!empty($subcategories)) {
echo '<div class="fixed-row clearfix dynamic-fixedRow-735" id="row_order_2">';
foreach($subcategories as $subcat) {
if(get_queried_object()->term_id == $subcat->term_id) $current = ' current-cat'; else $current = '';
echo '
<div class="box cat-item cat-item-'.$subcat->name.$current.'" style="min-height: 231px; margin-bottom:10px"><h5>
'.$subcat->name.'
</h5></div>';
}

Resources