Search code examples
phpwordpresswoocommerceproducthook-woocommerce

Show Product Custom Field in the WooCommerce Category Pages


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>';

}
  1. How can I show the product custom field if present, if not product excerpt, I don't want to show both of them.
  2. Also, how can I limit custom fields word’s or characters number
  3. How would I get the product custom field to show under the product title but above the price?

Solution

  • 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: