php – 在商店页面上为产品标题添加一定间隔的中断
我试图在我的商店循环中获得更多一致的网格布局.
产品标题跨越1或2行,具体取决于字符串长度,因此如果字符串长度低于强制它与下一行重叠的数量,我想添加一个中断”,这样它就不会影响整体商店循环页面的间距/ 这是我目前尝试过的代码: <?php echo "test"; $title = get_the_title(); if ( strlen($title) < 29 ) { echo '<br>'; } ?> 我把它放在content-product.php的woocommerce模板中,但它不起作用. 我的代码是否正确? 任何帮助将不胜感激. 谢谢 解决方法
此功能部分基于this answer和 这里我已经包含了您的限制字符串长度,但它也基于复杂的“字长”检测,以避免中断字: 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文件中,或者也可以放在任何插件文件中. 此代码经过测试和运行. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |