限制 Woocommerce 中的产品简短描述长度

use*_*498 6 php wordpress product woocommerce hook-woocommerce

我在我的 WordPress 网站上使用以下代码来缩短我在 WooCommerce 上的描述摘录,如果我输入 14 个或更少的字符,它就可以正常工作。一旦我输入超过 14 个字符,它就会显示完整的简短描述。

add_action( 'woocommerce_after_shop_loop_item_title', 'lk_woocommerce_product_excerpt', 35, 2);
if (!function_exists('lk_woocommerce_product_excerpt'))
{
    function lk_woocommerce_product_excerpt()
    {
        $content_length = 14;
        global $post;
        $content = $post->post_excerpt;
        $wordarray = explode(' ', $content, $content_length + 1);
        if(count($wordarray) > $content_length) :
            array_pop($wordarray);
            array_push($wordarray, '...');
            $content = implode(' ', $wordarray);
            $content = force_balance_tags($content);
            $content = substr($content, 0, 14);

        endif;
        echo "<span class='excerpt'><p>$content...</p></span>";
    }
}
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激。

谢谢。

Loi*_*tec 4

您的代码正在计算带有空格的字母,而下面的代码正在计算没有空格的单词。请查看这个正在运行的 php 文件 (这里是你的代码在包含 25 个单词的字符串上的结果,我的也是如此)。那么这段代码就可以如你所愿地正常工作:

\n\n
add_action( \'woocommerce_after_shop_loop_item_title\', \'shorten_product_excerpt\', 35 );\nfunction shorten_product_excerpt()\n{\n    global $post;\n    $limit = 14;\n    $text = $post->post_excerpt;\n    if (str_word_count($text, 0) > $limit) {\n        $arr = str_word_count($text, 2);\n        $pos = array_keys($arr);\n        $text = substr($text, 0, $pos[$limit]) . \'...\';\n        // $text = force_balance_tags($text); // may be you dont need this\xe2\x80\xa6\n    }\n    echo \'<span class="excerpt"><p>\' . $text . \'</p></span>\';\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n
\n\n

或者您可以使用下面线程中的函数,如下所示:

\n\n
if (!function_exists(\'lk_limit_text\'))\n{\n    function lk_limit_text($text, $limit) {\n        if (str_word_count($text, 0) > $limit) {\n            $words = str_word_count($text, 2);\n            $pos = array_keys($words);\n            $text = substr($text, 0, $pos[$limit]) . \'...\';\n        }\n        return $text;\n    }\n}\n\nadd_action( \'woocommerce_after_shop_loop_item_title\', \'lk_woocommerce_product_excerpt\', 35, 2);\nif (!function_exists(\'lk_woocommerce_product_excerpt\'))\n{\n    function lk_woocommerce_product_excerpt()\n    {\n        global $post;\n        $content = $post->post_excerpt;\n        // $content = force_balance_tags($content); // may be you dont need this\xe2\x80\xa6\n        echo \'<span class="excerpt"><p>\' . lk_limit_text( $content, 14 ) . \'</p></span>\';\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

这应该有效\xe2\x80\xa6

\n\n

该代码基于以下线程:How can I truncate a string to the front 20 Words in PHP?

\n

  • @user3612498是的,当然,你可以用`$post-&gt;post_content;`替换`$post-&gt;post_excerpt;`... (2认同)