I'm new to WooCommerce and I have tried the following code to show product custom field.
add_action( 'woocommerce_after_shop_loop_item_title', 'bbloomer_woocommerce_product_excerpt', 35 );
function bbloomer_woocommerce_product_excerpt() {
global $post;
if ( is_home() || is_shop() || is_product_category() || is_product_tag() ) {
echo '<span class="excerpt">';
echo get_post_meta( $post->ID, 'customtext', true );
echo '</span>';
}
}
I also have this code to show the product excerpt.
add_action( 'woocommerce_after_shop_loop_item_title', 'output_product_excerpt', 20 );
function output_product_excerpt() {
global $post;
echo '<div class="my-excerpt">'.wp_trim_words($post->post_excerpt,50).'</div>';
}
To display your product custom field, or if empty, the product short description instead, in WooCommerce Category Pages just after the product title and limiting the number of displayed words, use the following:
add_action( 'woocommerce_after_shop_loop_item_title', 'display_woocommerce_product_excerpt', 20 );
function display_woocommerce_product_excerpt() {
global $product;
if ( is_product_category() ) {
$excerpt = $product->get_meta('customtext');
if ( empty($excerpt) ) {
$excerpt = $product->get_short_description();
}
// Set the number of words to display
$num_words = 20;
printf( '<span class="excerpt">%s</span>', wp_trim_words($excerpt, $num_words) );
}
}
Code goes in functions.php file of your child theme (or in a plugin). Tested and works.
References:
wp_trim_words()
: Trims text to a certain number of words.woocommerce_after_shop_loop_item_title
, showing what is displayed, where and how.