在 WooCommerce 单个产品页面描述上添加一个 "read more" 按钮

Add a "read more" button on WooCommerce single product page description

我的商店有很长的产品描述,我想截断描述以显示 100 个字,然后显示一个显示“阅读更多”和“阅读更少”的按钮。

实际上我正在使用 答案代码,它可以通过特定的字数来限制简短描述的长度并且有效。

这需要对现有代码进行细微调整,而不是遗漏一些 $content,而是保留所有 $content,但仅显示其中的一部分,直到单击阅读按钮。

然后它使用 jQuery 控制读取 more/less 按钮,其中显示全部 $content 或仅显示部分。

注意: CSS(样式)和进一步的 jQuery 调整取决于主题。此答案包含阅读更多/更少按钮的基础。每个主题都有不同的特定要求,因此 display/functionality 的进一步改编必须由您自己提供

通过代码中提供的注释标签进行解释

// Shorten product long descrition with read more button
function filter_the_content( $content ) {
    // Only for single product pages
    if( ! is_product() ) return $content;

    // Set the limit of words
    $limit = 14;
    
    // Strip p tags if needed
    $content = str_replace( array( '<p>', '</p>' ), '', $content );

    // If the content is longer than the predetermined limit
    if ( str_word_count( $content, 0 ) > $limit ) {
        // Returns an associative array, where the key is the numeric position of the word inside the string and the value is the actual word itself
        $arr = str_word_count( $content, 2 );
        
        // Return all the keys or a subset of the keys of an array
        $pos = array_keys( $arr );
        
        // First part
        $text = '<p>' . substr( $content, 0, $pos[$limit] ) . '<span id="dots">...</span>';
        
        // More part
        $text .= '<span id="more">' . substr( $content, $pos[$limit] ) . '</span></p>';
        
        // Read button
        $text .= '<button id="read-button"></button>';
        
        $content = force_balance_tags( $text ); // needded
    }
    ?>
    <script type="text/javascript">
        jQuery(document).ready( function ($) {
            // Settings
            var read_more_btn_txt = 'Read more';
            var read_less_btn_txt = 'Read less';
            
            // Selectors
            var more = '#more';
            var read_button = '#read-button';
            var dots = '#dots';
            
            // On load
            $( more ).hide();
            $( read_button ).html( read_more_btn_txt );

            // On click
            $( read_button ).on( 'click', function() {
                if ( $( more ).is( ':hidden' ) ) {
                    $( more ).show();
                    $( dots ).hide();
                    $( read_button ).html( read_less_btn_txt );
                } else {
                    $( more ).hide();
                    $( dots ).show();
                    $( read_button ).html( read_more_btn_txt );
                }
            });

        });
    </script>
    <?php
    return $content;
}
add_filter( 'the_content', 'filter_the_content', 10, 1 );