在Woocommerce的长产品描述中添加"read more" / "read less"按钮:当不需要按钮时如何隐藏该按钮?



我正在一家Woomcommerce商店工作,那里的产品具有不同的描述长度。 我添加了一个"阅读更多"/"阅读更少"按钮,适用于较长的产品描述。 但是,在较短的描述中,该按钮是可见的,但显然没有任何作用,因为没有什么可切换的。 如何隐藏简短描述中的按钮?

这是新模板/单产品/简短描述的 PHP.php


if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
global $post;
$short_description = apply_filters( 'woocommerce_short_description', $post->post_excerpt );
if ( ! $short_description ){
return;
}
?>
<div class="woocommerce-product-details__short-description" itemprop="description-container">
<div class="product-description rte" itemprop="description">
<?php echo $short_description; // WPCS: XSS ok. ?>
</div>
<a class="readmore" href="#"><?php echo 'Read more...'?></a>
</div>

这是javascript:

$(document).ready(function () {
$('.readmore').click(function (event) {
event.preventDefault();
var description = document.querySelector('.product-description');
console.log(description.style.height)
if (description.style.height === ''){
description.style.height = 'auto';
} else if (description.style.height === 'auto'){
description.style.height = '';
}
else{
description.style.height = '92px';
}
$(this).text($(this).text() == 'Read less...' ? 'Read more...' : 'Read less...');
});
});

所以现在阅读更多/阅读更少切换完美地工作,但我真的很想知道如何在不必要的简短描述中隐藏它! 谢谢!

我忘了包含代码来检查长度。模板中正确的 PHP 应该是

if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
global $post;
$short_description = apply_filters( 'woocommerce_short_description', $post->post_excerpt );
if ( ! $short_description ){
return;
}
?>
<div class="woocommerce-product-details__short-description" itemprop="description-container">
<div class="product-description rte" itemprop="description">
<?php echo $short_description; // WPCS: XSS ok. ?>
</div>
<?php 
if (strlen($short_description) > 250){
?>
<a class="readmore" href="#">
<?php echo 'Read more...';
}?></a>
</div>

它现在可以工作,仅在描述大于 250 个字符时显示读取更多。

最新更新