【问题标题】:How to truncate characters in product description with WooCommerce如何使用 WooCommerce 截断产品描述中的字符
【发布时间】:2014-01-19 15:00:35
【问题描述】:

我发现了如何在 WooCommerce 中为产品的缩略图添加简短描述,但是如何将它们截断到一定长度,比如 30 个字符。 所有与编辑 functions.php 文件有关的答案都没有提到在文件中放置代码的位置。

我的functions.php文件中的代码是:

add_action('woocommerce_after_shop_loop_item_title','add_title_description',9);
function add_title_description(){
  echo get_post_meta($product->id, 'title-description', true)? '<span class="title-description">' . get_post_meta($product->id, 'title-description', true) . '</span><br />' : '';
}

【问题讨论】:

    标签: php wordpress woocommerce


    【解决方案1】:

    使用substr()

    add_action('woocommerce_after_shop_loop_item_title','add_title_description',9);
    
    function add_title_description()
    {
        $titleDescription = get_post_meta($product->id, 'title-description', true);
    
        if( !empty($titleDescription) )
        {
            if( strlen($titleDescription) > 30 )
                $titleDescription = substr($titleDescription, 30);
    
                printf('<span class="title-description">%s</span><br />', $titleDescription);
            }
    }
    

    【讨论】:

      【解决方案2】:

      我的实现抓取前 2 个句子而不是字符数。

      /**
      * Echo Truncated String
      *
      * @param  string $string
      * @return string
      */
      
      function add_title_description( $titleDescription ) {
      global $product;
      
          $titleDescription = get_post_meta( $product->id, 'title-description', true );
          
          // combine first 2 sentences
          $sentence = preg_split( '/(\.|!|\?)\s/', $titleDescription, 3, PREG_SPLIT_DELIM_CAPTURE );
          
          echo $titleDescription ? '<span class="title-description">' . $sentence[0] . $sentence[3] . '</span><br />' : '';
      
      }
      
      
      add_action( 'woocommerce_after_shop_loop_item_title', 'add_title_description', 4, 1 );
      

      【讨论】:

        【解决方案3】:

        我添加了这个:

            function wcs_excerpt_length( $length ) {
             return 15;
        }
        add_filter( 'product_description_length', 'wcs_excerpt_length' );
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-07-27
          • 2016-10-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-09-23
          • 1970-01-01
          • 2016-04-14
          相关资源
          最近更新 更多