Get the permalink from a loop displaying custom taxonomy titles and images - php

I have a custom post type called projects and a custom taxonomy attached to that called sectors. I have also added the ability to add an image to each taxonomy using Advanced Custom Fields.
I'm displaying a list of the sectors on the homepage of my site which consists of the title of the taxonomy along with its image here:
So far, so good...
I'm struggling with surrounding either the image or title with the permalink for the taxonomy. I'd like to be able to click on it and it takes me to a page showing all of the projects inside that sector.
My loop is as follows:
<div class="container">
<div class="row no-gutters">
<?php
// loop through terms of the Sectors Taxonomy
$getArgs = array(
'parent' => 0,
'order' => 'DESC',
'orderby' => 'count',
'hide_empty' => false,
);
// get the taxonomy we are going to loop through.
$taxonomy = get_terms('sectors', $getArgs);
$terms = get_terms($taxonomy);
// Start the loop through the terms
foreach ($taxonomy as $term) {
// Get acf field Name
$image = get_field('sector_image', $term );
$url = $image['url'];
$title = $image['title'];
$alt = $image['alt'];
// which size?
$size = 'large';
$thumb = $image['sizes'][ $size ];
?>
<div class="col-md-6">
<div class="sector-item-container" style="position: relative;">
<div class="box-overlay"><?php echo $term->name; ?></div><!-- box overlay -->
<a href="<?php the_permalink(); ?>">
<img src="<?php echo $thumb; ?>" alt="<?php echo $alt; ?>" title="<?php echo $title; ?>" />
</a>
</div>
</div>
<?php } // end foreach ?>
</div>
</div>
I've tried adding tags like this around the elements I want to be clickable:
<a href="<?php the_permalink(); ?>">
</a>
or
<a href="<?php echo get_term_link($term->slug, $taxonomy); ?>">
</a>
But they don't seem to pull the links through...
Can anyone see what I'm doing wrong? I appreciate any insight at all :)
***** EDIT ***************
This seems to show a list of the taxonomies and also apply the link to them... so it's somehow a mix of both I need I think, this following code works but without the images!...
<?php
$taxonomy = 'sectors';
$terms = get_terms($taxonomy); // Get all terms of a taxonomy
if ( $terms && !is_wp_error( $terms ) ) :
?>
<div class="container-flex">
<div class="row no-gutters">
<?php foreach ( $terms as $term ) { ?>
<div class="col-md-6">
<div class="sector-item-container" style="position: relative;">
<a href="<?php the_permalink(); ?>" rel="bookmark" title="<?php the_title(); ?>">
<div>
<?php
if ( has_post_thumbnail() ) {
the_post_thumbnail('page-thumb-mine');
}
?>
<?php
$image = get_field('sector_image');
if( !empty($image) ): ?>
<img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />
<?php endif; ?>
</div>
</a>
<div class="sector-item-title">
<a href="<?php echo get_term_link($term->slug, $taxonomy); ?>">
<h4><?php echo $term->name; ?></h4>
</a>
</div>
</div>
</div>
<?php } ?>
</div>
</div>
<?php endif;?>
<?php wp_reset_postdata(); ?>

This is from the codex on https://developer.wordpress.org/reference/functions/get_term_link/.
$terms = get_terms( 'species' );
echo '<ul>';
foreach ( $terms as $term ) {
// The $term is an object, so we don't need to specify the $taxonomy.
$term_link = get_term_link( $term );
// If there was an error, continue to the next term.
if ( is_wp_error( $term_link ) ) {
continue;
}
// We successfully got a link. Print it out.
echo '<li>' . $term->name . '</li>';
}
echo '</ul>';
For your specific case, try swapping the above with this: $terms = get_terms( 'sectors' );
Edit:
As for your images, retrieve them with get_field('sector_image', $id_of_term_or_post_or_whatever); Be sure to echo it.
$image = get_field('sector_image', id_of_term_or_post_or_whatever);
echo $image; //this might be $image['url'] or whatever, depending on how you set up ACF

Ok, I think I actually managed to combine the two bits of code like this and it seems to work!
<?php
$taxonomy = 'sectors';
$terms = get_terms($taxonomy); // Get all terms of a taxonomy
if ( $terms && !is_wp_error( $terms ) ) :
?>
<div class="container-flex">
<div class="row no-gutters">
<?php foreach ( $terms as $term ) {
$image = get_field('sector_image', $term );
$url = $image['url'];
$title = $image['title'];
$alt = $image['alt'];
$size = 'large';
$thumb = $image['sizes'][ $size ];
?>
<div class="col-md-6">
<div class="sector-item-container" style="position: relative;">
<a href="<?php echo get_term_link($term->slug, $taxonomy); ?>">
<div>
<img src="<?php echo $thumb; ?>" alt="<?php echo $alt; ?>" title="<?php echo $title; ?>" />
</div>
</a>
<div class="sector-item-title">
<a href="<?php echo get_term_link($term->slug, $taxonomy); ?>">
<h4><?php echo $term->name; ?></h4>
</a>
</div>
</div>
</div>
<?php } ?>
</div>
</div>
<?php endif;?>
<?php wp_reset_postdata(); ?>

Related

Wordpress - Get the thumbnail of the latest post for each category in archive page

I have a custom post type archive page that lists the categories associated with that post type. I would like to include the thumbnail of the latest post in each category as the thumbnail for the said category.
So far I have managed to create the list of the categories, but my attempt at including the latest post thumbnail has resulted in the latest post for the post type as a whole being returned for all categories.
This is how I currently have it below:
<?php if ( $terms && !is_wp_error( $terms ) ) :
?>
<ol class="lister__list">
<?php foreach ( $terms as $term ) { ?>
<li class="lister__item item">
<article class="lister__article">
<a href="<?php echo get_term_link($term->slug, $taxonomy); ?>" class="item__link" title="Permalink to <?php the_title(); ?>" rel="bookmark">
<!--image-->
<?php $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'thumb' );?>
<?php if ( has_post_thumbnail() ) { ?>
<img src="<?php echo $thumb[0]; ?>" width="<?php echo $thumb[1];?>" height="<?php echo $thumb[2];?>" />
<?php } else { ?>
nope
<?php }?>
<h2 class="item__title"><?php echo $term->name; ?></h2>
</a>
</li>
<?php } ?>
</ol>
<?php endif;?>
any help much appreciated.

Display woocommerce product variations as single products on shop page and ajax load more

I have displayed wc product's variations as a single product.
Here is link: https://hueslabsstage.wpengine.com/store/
also, you need credentials:
login: hueslabsstage
password: 11test11
I have an issue with ajax load more function. I am using WooCommerce Load More Products by BeRocket. For example, when I choose 2 products to show on load more it really shows 2 products, but with all variations. For example, I have 4 products, the first one and the second one with 2 variations, so the plugin shows me 4 items on the shop page(2 products with 2 variations).
So, I need to display each variation as a single product in the way the plugin sees products. In order to when I choose 2 products to show, the plugin should display 2 variations of the product, instead of 2 products with them all variations.
Hope I explained my issue correctly.
My content-product.php:
<?php
if ($product->is_type('variable')): ?>
<?php
$unique_variations = [];
foreach($product->get_available_variations() as $key => $item) {
if (!variation_exists($item['attributes']['attribute_pa_color'], 'attribute_pa_color', $unique_variations)) {
$unique_variations[] = $item;
}
}
?>
<?php foreach($unique_variations as $variation):
$itemVariation = $variation['variation_id'];
?>
<?php
$meta = get_post_meta($variation['variation_id'], 'attribute_pa_color', true);
if (empty($meta)) {
continue;
}
$term = get_term_by('slug', $meta, 'pa_color');
$color = get_field('product_color', $term->taxonomy . '_' . $term->term_id);
$gallery = get_field('gallery', $variation['variation_id']);
$front_image = wp_get_attachment_image_src($variation['image_id'], 'product-thumbnail')[0];
$back_image = null;
if (!empty($gallery)) {
$back_image = $gallery[0]['sizes']['product-thumbnail'];
}
?>
<article class="<?php echo $outOfStock; ?>">
<?php if ($product_status_badge): ?>
<div class="product_badge">
<img src="<?php echo $product_status_badge; ?>" alt="Product status">
</div>
<?php endif; ?>
<div class="product_images">
<?php
if ( ! $product->managing_stock() && ! $product->is_in_stock() ){
?>
<div class="out_of_stock_overlay">Sold Out</div>
<?php
}
?>
<div class="product_image_items">
<figure>
<a href="<?php echo get_the_permalink() ?>?attribute_pa_color=<?php echo $meta ?>" title="<?php echo get_the_title(); ?>">
<img src="<?php echo $item['image']['url'];?>" alt="<?php echo get_the_title(); ?>" class="front_img">
<img src="<?php echo $back_image;?>" alt="<?php echo get_the_title(); ?>" data-test="<?php echo $back_image;?>" class="back_img">
</a>
<div class="product_arrows">
<div class="arrow_left">
<em class="fal fa-chevron-left"></em>
</div>
<div class="arrow_right">
<em class="fal fa-chevron-right"></em>
</div>
</div>
</figure>
</div>
</div>
<div class="product_top">
<div class="product_left">
<h3 class="product_title"><?php echo get_the_title(); ?></h3>
<div class="price">
<?php if ($product->is_type('variable')): ?>
<?php echo $product->get_variation_price() . " " . get_woocommerce_currency_symbol(); ?>
<?php else: ?>
<?php echo $product->get_price_html(); ?>
<?php endif; ?>
</div>
</div>
<?php if ($product->is_type('variable')): ?>
<?php
$unique_variations = [];
foreach($product->get_available_variations() as $key => $item) {
if (!variation_exists($item['attributes']['attribute_pa_color'], 'attribute_pa_color', $unique_variations)) {
$unique_variations[] = $item;
}
}
?>
<div class="product_right">
<ul class="product_variations_list">
<?php foreach($unique_variations as $variation): ?>
<?php
$meta = get_post_meta($variation['variation_id'], 'attribute_pa_color', true);
if (empty($meta)) {
continue;
}
$term = get_term_by('slug', $meta, 'pa_color');
$color = get_field('product_color', $term->taxonomy . '_' . $term->term_id);
$gallery = get_field('gallery', $variation['variation_id']);
$front_image = wp_get_attachment_image_src($variation['image_id'], 'product-thumbnail')[0];
$back_image = null;
if (!empty($gallery)) {
$back_image = $gallery[0]['sizes']['product-thumbnail'];
}
?>
<li class="<?php echo $variation['variation_id'] == $itemVariation ? 'active' : ''; ?>" data-variation-id="<?php echo $variation['variation_id']; ?>" data-variation-image="<?php echo $front_image; ?>" data-variation-back-image="<?php echo $back_image; ?>">
<a href="<?php echo get_the_permalink(); ?>?attribute_pa_color=<?php echo $term->slug;?>" title="<?php echo $term->name; ?>">
<em class="fas fa-certificate primary" style="color: <?php echo $color ;?>;"></em>
<em class="fas fa-certificate secondary"></em>
</a>
</li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
</div>
<div class="product_bottom">
<ul>
<?php foreach ($attributes as $attribute): ?>
<?php $image = get_field('image', 'pa_specifications_' . $attribute->term_id); ?>
<li>
<img src="<?php echo $image['url']; ?>" alt="<?php echo $attribute->name; ?>">
</li>
<?php endforeach; ?>
</ul>
</div>
</article>
<?php endforeach; ?>
<?php endif;
?>
archive-product.php is not changed :
if ( wc_get_loop_prop( 'total' ) ) {
while ( have_posts() ) {
the_post();
/**
* Hook: woocommerce_shop_loop.
*/
do_action( 'woocommerce_shop_loop' );
wc_get_template_part( 'content', 'product' );
}
}

Variable product image Will not display on single product view

My theme uses custom code to display the Woocommerce single product image but the variable product images will not display. The feature image shows and the gallery images show. When using the woocommerce standard template from product-image.php the variable image works but I do not want to use standard template because it does not work well with my theme (gallery image slider not working properly). here is the custom code below. Any idea what's missing or what can be done to get the variable images to show up?
Thanks in advance.
$image_size = array(500,600);
$url_image_default = ST_MaxShop_Assets::url('images/img-default.png');
$attachment_ids = $product->get_gallery_image_ids();
$post_thumbnail_id = $product->get_image_id();
$image_url = wp_get_attachment_image_src( get_post_thumbnail_id( $product->get_id(), apply_filters( 'single_product_large_thumbnail_size', 'shop_single' ) ) );
?>
<div class="<?php echo esc_attr( implode( ' ', array_map( 'sanitize_html_class', $wrapper_classes ) ) ); ?>" data-columns="<?php echo esc_attr( $columns ); ?>" style="opacity: 1; transition: opacity .25s ease-in-out;width:100%">
<div class="clearfix">
<figure class="woocommerce-product-gallery__wrapper">
<?php
if ( has_post_thumbnail() ) {
?>
<a class="jqzoom" href="<?php echo get_the_post_thumbnail_url($product->get_id() , array(1500,1800)); ?>" id="jqzoom" data-rel="gal-1">
<?php
$props = wc_get_product_attachment_props( get_post_thumbnail_id(), $post );
?>
<img src="<?php echo $image_url[0]; ?>" title="<?php echo esc_attr($props['title']); ?>" alt ="<?php echo esc_attr($props['alt'])?>">
<?php
?>
</a>
<?php
} else { ?>
<a class="jqzoom" href="<?php echo esc_url($url_image_default); ?>" id="jqzoom" data-rel="gal-1">
<?php
$dimensions = wc_get_image_size( $image_size ); ?>
<img src="<?php echo esc_url($url_image_default); ?>" width="<?php echo esc_attr( $dimensions['width'] ) ?> " height="<?php echo esc_attr( $dimensions['height'] ) ?> " alt="<?php esc_html_e('Image Default','maxshop')?>" title="<?php esc_html_e('product','maxshop')?>" />
<?php
?></a><?php
}
?>
</figure>
</div>
</div>
<?php
if($attachment_ids){
?>
<ul class="jqzoom-list">
<?php
if ( has_post_thumbnail() ) { ?>
<li>
<a class="zoomThumbActive" href="javascript:void(0)" data-rel="{gallery:'gal-1', smallimage: '<?php echo get_the_post_thumbnail_url($post -> ID,$image_size); ?>', largeimage: '<?php echo get_the_post_thumbnail_url($post->ID , array(1500,1800)); ?>'}">
<?php echo get_the_post_thumbnail( $post->ID, array(100,100)); ?>
</a>
</li>
<?php } ?>
<?php
foreach ($attachment_ids as $attachment_id){ ?>
<li>
<a href="javascript:void(0)" data-rel="{gallery:'gal-1', smallimage: '<?php echo esc_url(wp_get_attachment_image_url($attachment_id,$image_size)); ?>', largeimage: '<?php echo esc_url(wp_get_attachment_image_url($attachment_id, array(1500,1800))); ?>'}">
<?php
echo wp_get_attachment_image($attachment_id,array(100,100)); ?>
</a>
</li>
<?php
}
?>
</ul>
<?php
}
}
as i can see you are getting only the main product image at this line
$attachment_ids = $product->get_gallery_image_ids();
and you are looping through all of them withing your code and in order to get the variation images you need to add the following code as follow:
$image_size = array(500,600);
$variation_image_id = array();
$attachment_ids = $product->get_gallery_image_ids();
$variations = $product->get_available_variations();
foreach ( $variations as $variation ) {
$variation_image_id[]= $variation["image_id"];
}
$attachment_ids = array_merge( $variation_image_id , $attachment_ids);
$post_thumbnail_id = $product->get_image_id();

WordPress echo taxonomy of custom post type in wordpress loop

I have created a Custom Post Type product and for this CPT I've also created a taxonomy with the name products_types.
Now on my overview page of all the products I would like to echo out the product type that was given to the product. But I keep getting bool(false).
My code:
<div class="row">
<?php
$loop = new WP_Query( array( 'post_type' => 'product') );
if ( $loop->have_posts() ) :
while ( $loop->have_posts() ) : $loop->the_post();
?>
<div class="col-md-4 col-lg-3 work">
<div class="category">
<?php
$category = get_the_terms('product', 'products_types');
var_dump($category);
echo $category;
?>
</div>
<a href="<?php the_permalink() ?>" class="work-box"> <img src="<?= get_field('image'); ?>" alt="">
<div class="overlay">
<div class="overlay-caption">
<p><?php echo the_title() ?></p>
</div>
</div>
</a>
</div>
<?php
endwhile;
endif;
wp_reset_postdata();
?>
</div>
Anyone can help me out here please?
You need to pass the Post ID or object in first parameter of get_the_terms(). Used get_the_ID() which return the post ID.
Example:
foreach (get_the_terms(get_the_ID(), 'products_types') as $cat) {
echo $cat->name;
}
How to print taxonomy terms of custom post type in WordPress loop?
<div class="row">
<?php
$loop = new WP_Query( array( 'post_type' => 'product') );
if ( $loop->have_posts() ) :
while ( $loop->have_posts() ) : $loop->the_post();
?>
<div class="col-md-4 col-lg-3 work">
<div class="category">
<?php
$terms = get_the_terms( get_the_ID(), 'products_types' );
if ( $terms && ! is_wp_error( $terms ) ) :
$category_links = array();
foreach ( $terms as $term ) {
$category_links[] = $term->name;
}
$categories = join( ", ", $category_links );
?>
<?php printf( esc_html( $categories ) ); ?>
<?php endif; ?>
</div>
<a href="<?php the_permalink() ?>" class="work-box"> <img src="<?= get_field('image'); ?>" alt="">
<div class="overlay">
<div class="overlay-caption">
<p><?php echo the_title() ?></p>
</div>
</div>
</a>
</div>
<?php
endwhile;
endif;
wp_reset_postdata();
?>
</div>

How to show text if no posts from query?

I have a custom WordPress post type, and want to make so if there are no posts in the query to display, it shows a message of saying no posts were found, I've tried a few suggestions but nothing seems to be working so far.
Full Code of the relevant section:
<?php
$k=0;
$args = array(
'post_type'=>'portfolios',
'posts_per_page'=>5,
'order'=>'DESC'
);
$the_query = new WP_Query($args);
while($the_query->have_posts()):$the_query->the_post();
$k++;
if($k==1){
$color= 'gray';
}else if($k==2){
$color= 'blue';
}else if($k==3){
$color= 'green';
}else if($k==4){
$color= 'light-blue';
}else if($k==5){
$color= 'yellow';
}
?>
<div itemprop="exampleOfWork" class="col-xs-12 col-sm-4 portfolio-item">
<div class="portfolio-holder">
<?php
if(has_post_thumbnail()){
$image_id = get_post_thumbnail_id();
$image_url = wp_get_attachment_image_src($image_id,'singleport',true);
?>
<figure><a itemprop="url" href="<?php the_permalink();?>"><img src="<?php echo $image_url[0];?>" alt="Portfolio image" /></a></figure>
<?php }else{ ?>
<figure><a itemprop="url" href="<?php the_permalink();?>"><img src="<?php echo esc_url( get_template_directory_uri() );?>/assets/images/noimage.jpg" alt="No image" /></a></figure>
<?php } ?>
<h6 itemprop="name"><?php the_title(); ?></h6>
<span itemprop="genre"><?php the_field('name');?></span>
<div class="transparentbg <?php echo $color; ?>">
<?php
$image = get_field('logo');
if( !empty($image) ): ?>
<a itemprop="url" href="<?php the_permalink();?>">
<img src="<?php echo $image['url']; ?>" alt="logo" />
</a>
<?php endif; ?>
<a href="<?php the_permalink();?>" class="info">
<img itemprop="image" src="<?php echo esc_url( get_template_directory_uri() );?>/assets/images/port-hover-bg.png" alt="Port hover bg" /><br />
<img itemprop="image" src="<?php echo esc_url( get_template_directory_uri() );?>/assets/images/search-icon.png" height="20" width="20" alt="Search icon">
</a>
</div>
</div>
</div>
<?php endwhile;wp_reset_query();?>
</div>
</div>
</section>
How can we make it so, if there's no posts, it echo's a message?
Add a check -
if (!empty($the_query->have_posts())) {
while(...) {...}
} else {
echo "No Posts!";
}
Issue
You want to use WP Query class for fetching a particular type of posts ( based on custom fields ), and if it returns no posts at all, it should display a message.
Solution
$the_query = new WP_Query( $args );
Where "$args" is your list of parameters for WP_Query constructor.
Now $the_query is an object of class type WP-Query. Hence it contains a function that will return whether there is any post matching your particular query. If there is at least one post, it will return True, else it will return False.
That function to check if there are any posts matching your queries is have_posts() .
Usage is ObjectName->have_posts();
in your specific case it is
$the_query->have_posts();
This will return true or false based on the query ( ie, arguments you supply using $arg variable ).
hence:
if($the_query->have_posts()) {
//There are posts matching the query
}
else
{
//There are no posts matching the query
}
You can use the below code ( You will have to modify this, but still a good start ).
<?php
$args = array(
'post_type'=>'portfolios',
'posts_per_page'=>5,
'order'=>'DESC'
);
$the_query = new WP_Query( $args ); ?>
<?php if ( $the_query->have_posts() ) : ?>
<!-- pagination here -->
<!-- the loop -->
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<h2><?php the_title(); ?></h2>
<?php endwhile; ?>
<!-- end of the loop -->
<!-- pagination here -->
<?php wp_reset_postdata(); ?>
<?php else : ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>
Reference : https://codex.wordpress.org/Class_Reference/WP_Query
You need to add if condition before while loop like that way:
<?php
$k=0;
$args = array(
'post_type'=>'portfolios',
'posts_per_page'=>5,
'order'=>'DESC'
);
$the_query = new WP_Query($args);
if( $the_query->have_posts() ) {
while($the_query->have_posts()):
// your code
<?php endwhile;
} else {
echo "No data found.";
}
wp_reset_query();
?>
<?php
$k=0;
$args = array(
'post_type'=>'portfolios',
'posts_per_page'=>5,
'order'=>'DESC'
);
$the_query = new WP_Query($args);
if($the_query->have_posts()):
while($the_query->have_posts()):$the_query->the_post();
$k++;
if($k==1){
$color= 'gray';
}else if($k==2){
$color= 'blue';
}else if($k==3){
$color= 'green';
}else if($k==4){
$color= 'light-blue';
}else if($k==5){
$color= 'yellow';
}
?>
<div itemprop="exampleOfWork" class="col-xs-12 col-sm-4 portfolio-item">
<div class="portfolio-holder">
<?php
if(has_post_thumbnail()){
$image_id = get_post_thumbnail_id();
$image_url = wp_get_attachment_image_src($image_id,'singleport',true);
?>
<figure><a itemprop="url" href="<?php the_permalink();?>"><img src="<?php echo $image_url[0];?>" alt="Portfolio image" /></a></figure>
<?php }else{ ?>
<figure><a itemprop="url" href="<?php the_permalink();?>"><img src="<?php echo esc_url( get_template_directory_uri() );?>/assets/images/noimage.jpg" alt="No image" /></a></figure>
<?php } ?>
<h6 itemprop="name"><?php the_title(); ?></h6>
<span itemprop="genre"><?php the_field('name');?></span>
<div class="transparentbg <?php echo $color; ?>">
<?php
$image = get_field('logo');
if( !empty($image) ): ?>
<a itemprop="url" href="<?php the_permalink();?>">
<img src="<?php echo $image['url']; ?>" alt="logo" />
</a>
<?php endif; ?>
<a href="<?php the_permalink();?>" class="info">
<img itemprop="image" src="<?php echo esc_url( get_template_directory_uri() );?>/assets/images/port-hover-bg.png" alt="Port hover bg" /><br />
<img itemprop="image" src="<?php echo esc_url( get_template_directory_uri() );?>/assets/images/search-icon.png" height="20" width="20" alt="Search icon">
</a>
</div>
</div>
</div>
<?php
endwhile;
else:
echo "Your message goes here";
endif;
wp_reset_query();
?>
</div>
</div>
</section>
Adding if condition will do it.

Categories