I searched here a lot, but the decisions are for post attachments.
I have gallery on each product page.
I want to make custom data attribute for each thumbnail, that has to be equal to alt or caption value.
There’s the code, a standard attachments loop, and the script what I want to do
<div class="gallery_thumbs show-all-thumbs">
<?php
$attachment_ids = $product->get_gallery_attachment_ids();
if ( ! empty( $attachment_ids ) ) { ?>
<?php
foreach( $attachment_ids as $attachment_id ) {
//There I try to get alt of each image
$image_alt = get_post_meta( $attachment_id, '_wp_attachment_image_alt', true);?>
<div class="woocommerce-product-gallery__item">
<a href="<?php echo wp_get_attachment_image_url( $attachment_id, 'full' ); ?>">
<?php
echo wp_get_attachment_image( $attachment_id, 'full' );?>
</a>
<div class="caption">
<?php
echo $image_alt;
?>
</div>
</div>
<script>
var caption = <?php echo $image_alt;?>
jQuery( "img" ).each(function() {
jQuery(this).attr('data-name', caption);
});
</script>
<?php
}
}
?>
</div>
Instead of var value I see data-name="[object Object]". Like it’s empty.
How to get this attribute correctly, to use its value in my custom data-name attribute?
2
Answers
"[object Object]" doesn’t mean it’s empty. It means it’s an object, try to console.log it.
Either way, I think this line should be:
It can be done using the hook. here is an example code, modify it as per your need/use.