我在这里找了很多,但这些决定都是为了张贴附件。我在每个产品页上都有图片库。我希望为每个缩略图创建自定义数据属性,该属性必须等于alt或标题值。
这是代码,一个标准附件循环,以及我想要做的脚本
<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>我看到的不是var值,而是data-name="object Object“。好像是空的。如何正确获取该属性,如何在我的自定义数据名属性中使用它的值?
发布于 2022-09-03 21:14:43
“对象对象”并不意味着它是空的。它意味着它是一个对象,尝试console.log它。不管怎样,我认为这句话应该是:
var caption = <?php echo json_encode($image_alt); ?>;发布于 2022-09-09 18:02:08
这可以用钩子来完成。下面是一个示例代码,根据您的需要/使用对其进行修改。
add_filter(
'woocommerce_gallery_image_html_attachment_image_params',
function( $params, $attachment_id ) {
// Get the alt text from attachment ID.
$alt_text = trim( wp_strip_all_tags( get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ) ) );
// Get the attachment caption.
$caption = _wp_specialchars( get_post_field( 'post_excerpt', $attachment_id ), ENT_QUOTES, 'UTF-8', true );
// Get the attachment title.
$title = _wp_specialchars( get_post_field( 'post_title', $attachment_id ), ENT_QUOTES, 'UTF-8', true );
// Add custom data attributes in parameters.
$params['data-custom-attr-1'] = $alt_text;
$params['data-custom-attr-2'] = $caption;
$params['data-custom-attr-1'] = $title;
return $params;
},
10,
2
);https://stackoverflow.com/questions/73594938
复制相似问题