最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

functions - Remove text after a dot and a colon in Woocommerce product title

programmeradmin1浏览0评论

In my product title, I would like to remove all the text content after the first dot "." or colon ":".

For instance I would like to transform : Theodore Deck : The Peter Marino Collection => Theodore Deck

I tried this code from this articlebut without success.

function explode_parts($title, $id){
    $parts = explode(' : ', $title);
    $before = $parts[0]; //before the :
    $after = $parts[1]; //after the : 
    return (whatever);
}

add_filter('the_title', 'explode_parts');

Thanks for your help!

In my product title, I would like to remove all the text content after the first dot "." or colon ":".

For instance I would like to transform : Theodore Deck : The Peter Marino Collection => Theodore Deck

I tried this code from this articlebut without success.

function explode_parts($title, $id){
    $parts = explode(' : ', $title);
    $before = $parts[0]; //before the :
    $after = $parts[1]; //after the : 
    return (whatever);
}

add_filter('the_title', 'explode_parts');

Thanks for your help!

Share Improve this question asked Jun 8, 2020 at 9:27 PardaiglePardaigle 52 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

Try using following code:

add_filter('the_title', 'mod_product__title', 10, 2);
function mod_product__title($title, $id) {

    if( is_product() ) {
        if(preg_match('/[^(:|.)]*/', $title, $matches)){
            return trim($matches[0]);
        }else{
            return $title;
        }
    }
    return $title;
}

Here I'm using regex to match . or : . Regex will match only the first occurrence and return the text before it. Then I'm using trim() to get rid of any extra trailing space. If it doesn't match anything then it will return the full title.

UPDATE

Following code checks up wheather it's admin list or front-end and modifies title accordingly

add_filter('the_title', 'mod_product__title', 10, 2);
function mod_product__title($title, $id) {
    global $pagenow;
    if ( $pagenow != 'edit.php' && get_post_type( $id ) == 'product' ) {
        if(preg_match('/[^(:|.)]*/', $title, $matches)){
            return trim($matches[0]);
        }else{
            return $title;
        }
    }
    return $title;
}
发布评论

评论列表(0)

  1. 暂无评论