這個答案是基於「標題長度」和「字長度「,以避免打破一個字。
此功能部分基於this answer和woocommerce_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>';
}
}
}
此代碼放在功能。你的活動兒童主題(或主題)的php文件或任何插件文件。
該代碼已經過測試並且可以正常工作。
難道我沒有辦法讓這項工作如何我最初的目的? 就好像我縮短了一些產品名稱,它不會真的對用戶有意義 –