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!

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;
}
| improve this answer | |
  • Thanks for your help, I've put this code in my function.php file but it seems not working. I still see text after : or . in the product title. Any idea why? – Pardaigle Jun 8 at 12:53
  • I've modified the answer. check please. – Sabbir Hasan Jun 8 at 20:14
  • It works, thanks a lot! – Pardaigle Jun 10 at 8:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.