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!
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()
orthe_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 . ' ';
} else {
return $product_name;
}
}
Code goes in function.php file of your active child theme (or active theme).
Tested and works.
use this:
$str = "Remove First Word";
$words = explode(' ', $str);
unset($words[0]);
echo join(' ', $words);
The explode
function returns an array with each words.
The unset
function remove the first word contained in the array $words
.
Finally, join
print all $words
joined by space .
Could you try using this?
if ( ! function_exists( 'woocommerce_template_loop_product_title' ) ) {
/**
* Removes first word in WooCommerce product_title
* @var $tag
*/
function woocommerce_template_loop_product_title() {
$tag = is_product_taxonomy() || is_shop() ? 'h2' : 'h3';
echo apply_filters( 'woocommerce_template_loop_product_title', '<' . $tag . ' class="woocommerce-loop-product__title">' . substr(strstr(get_the_title()," "), 1) . '</' . $tag . '>');
}
/**
* Removes first word in WooCommerce product page product_title
* @var $tag
*/
function woocommerce_single_product_summary() {
$tag = 'h1';
echo apply_filters(woocommerce_single_product_summary, '<' . $tag . ' class="product_title entry-title">' . substr(strstr(get_the_title()," "), 1) . '</' . $tag . '>');
}
}
Hopefully this works out for you, haven't tested it.