微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 在商店页面上为产品标题添加一定间隔的中断

我试图在我的商店循环中获得更多一致的网格布局.

产品标题跨越1或2行,具体取决于字符串长度,因此如果字符串长度低于强制它与下一行重叠的数量,我想添加一个中断”,这样它就不会影响整体商店循环页面的间距/

这是我目前尝试过的代码

<?PHP
    echo "test";
    $title = get_the_title();
    if ( strlen($title) < 29 )
    {
        echo '<br>';
    }
?>

我把它放在content-product.PHP的woocommerce模板中,但它不起作用.

我的代码是否正确?

任何帮助将不胜感激.

谢谢

解决方法

This answer is based on both “title length” an “words length”,to avoid breaking a word.

功能部分基于this answerwoocommerce_template_loop_product_title() WooCommerce本机功能,用于content-product.php WooCommerce模板,以在商店页面显示标题.

这里我已经包含了您的限制字符串长度,但它也基于复杂的“字长”检测,以避免中断字:

if (  ! function_exists( 'woocommerce_template_loop_product_title' ) ) {

    // Show the product title in the product loop. By default this is an <h3> html tag.

    function woocommerce_template_loop_product_title() {

        // Define the lenght limit for title (by line)
        $limit = 29;

        $title = get_the_title();
        $lenght = strlen($title);

        // 1. The title length is higher than limit

        if ( $lenght >= $limit ) {

            $title_arr1 = array();
            $title_arr2 = array();
            $sum_length_words = -1;

            // an array of the words of the title
            $title_word_arr = explode( ' ',$title );

            // iterate each word in the title
            foreach( $title_word_arr as $word ){
                // Length of current word (+1 space)
                $length_word = strlen($word) + 1;
                // Adding the current word lenght to total words lenght
                $sum_length_words += $length_word;
                // Separating title in 2 arrays of words depending on lenght limit
                if ( $sum_length_words <= $limit )
                    $title_arr1[] .= $word;
                else
                    $title_arr2[] .= $word;
            }
            // Converting each array in a string
            $splitted_title = implode(" ",$title_arr1). ' ('. strlen(implode(" ",$title_arr1)) .')';
            $splitted_title .= '<br>'; // adding <br> between the 2 string
            $splitted_title .= implode(" ",$title_arr2). ' ('. strlen(implode(" ",$title_arr2)) .')';
            echo '<h3>' . $splitted_title . '</h3>';

        // 2. The title length is NOT higher than limit

        } else {
            echo '<h3>' . $title . '</h3>';
        }

    }

}

代码位于活动子主题(或主题)的function.PHP文件中,或者也可以放在任何插件文件中.

代码经过测试和运行.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐