dongpang1898 2018-02-08 13:01
浏览 68
已采纳

从WooCommerce产品标题中删除第一个单词

Is it possible to remove the first word from the product title in WooCommerce? I've found some php code but I can't figure it out at the moment.

echo substr(strstr("Remove First Word"," "), 1);

That should echo "First Word". How would I do that for the WooCommerce product title? I appreciate all the help!

  • 写回答

3条回答 默认 最新

  • dongyuan8312 2018-02-08 13:39
    关注

    For product title in single product pages and archives pages:

    add_filter( 'the_title', 'custom_the_title', 10, 2 );
    function custom_the_title( $title, $post_id ){
        $post_type = get_post_field( 'post_type', $post_id, true );
        if( $post_type == 'product' || $post_type == 'product_variation' )
            $title = substr( strstr( $title, ' ' ), 1 );
    
        return $title;
    }
    

    Code goes in function.php file of your active child theme (or active theme).

    Tested and works.

    The product title uses WordPress function get_the_title() or the_title() to be displayed (as woocommerce product is a custom post type)… so the correct filter hook to be used is "the_title".

    But it will not really handle html tags (as this are something else in the templates).


    For cart and checkout pages:

    add_filter( 'woocommerce_cart_item_name', 'customizing_cart_item_name', 10, 3);
    function customizing_cart_item_name( $item_name, $cart_item, $cart_item_key ) {
        $product = $cart_item['data'];
        $product_permalink = $product->is_visible() ? $product->get_permalink( $cart_item ) : '';
    
        $product_name = $product->get_name();
        $product_name = substr( strstr( $product_name, ' ' ), 1 );
    
        if ( $product_permalink && is_cart() ) {
            return sprintf( '<a href="%s">%s</a>', esc_url( $product_permalink ), $product_name );
        } elseif ( ! $product_permalink && is_cart() ) {
            return $product_name . '&nbsp;';
        } else {
            return $product_name;
        }
    }
    

    Code goes in function.php file of your active child theme (or active theme).

    Tested and works.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line