You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WooCommerce产品描述Read more按钮位置错位修复方法

问题原因

按钮出现在内容块下方是因为拼接HTML结构时,<button>元素被放在了首个段落的闭合标签</p>外部,浏览器默认会将处于段落外的按钮渲染到整段内容下方,不符合预期位置。

修复方案

调整PHP部分的HTML拼接顺序,把按钮代码移动到段落闭合标签内部,放在省略号<span id="dots">的后方即可,按钮会直接出现在截断文本、省略号的紧邻位置。
可以直接替换使用下面修改后的完整代码:

// Shorten product long description 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>';
        // 按钮移到p标签内部、省略号后方
        $text .= '<button id="read-button" style="margin-left: 6px; border:none; background:none; color:#0066cc; cursor:pointer;"></button>';
        // More part
        $text .= '<span id="more">' . substr( $content, $pos[$limit] ) . '</span></p>';
        
        $content = force_balance_tags( $text );
    }
?>
<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 );
补充说明
  • 代码里给按钮加了基础行内样式,去掉默认按钮边框、背景,和普通文本链接视觉风格统一,可以根据自己的主题样式调整间距、颜色等参数。
  • 原有JS交互逻辑不需要修改,元素ID没有变动,展开/收起功能可以正常运行。
  • 如果需要保留产品描述原有的多段落结构,只需要去掉开头替换<p>标签的代码,调整截断逻辑只处理首个段落即可,当前修改已经完全满足「按钮放在省略号位置、紧跟首个p标签文本后」的需求。

内容的提问来源于stack exchange,提问作者Sam Jacka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.31 00:12:41