1

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

这是新模板/single-product/short-description.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...');
    });
});

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

4

1 回答 1

1

我忘了包含检查长度的代码。模板中正确的 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 个字符时才显示 readmore。

于 2019-07-11T20:16:08.487 回答