Ad

How Can I Optimize This Code To Display Custom Fields?

I am displaying several custom fields for Woocommerce products:

function fields() {

global $product;

$value1 = get_post_meta( $product->id, 'storage', true );
$value2 = get_post_meta( $product->id, 'delivery_date', true );
$value3 = get_post_meta( $product->id, 'mpn', true );
$value4 = get_post_meta( $product->id, 'color', true );
$value5 = get_post_meta( $product->id, 'sizes_available', true );
$value6 = get_post_meta( $product->id, 'country_of_origin', true );

if ( ! empty( $value1 ) ) {
echo '<div>Storage: '  . $value1 . '</div>';
}

if ( ! empty( $value2 ) ) {
echo '<div>Delivery: '  . $value2 . '</div>';
}

if ( ! empty( $value3 ) ) {
echo '<div>Manufacturer's product number: '  . $value3 . '</div>';
}

if ( ! empty( $value4 ) ) {
echo '<div>Color: '  . $value4 . '</div>';
}

if ( ! empty( $value5 ) ) {
echo '<div>Sizes: '  . $value5 . '</div>';
}

if ( ! empty( $value6 ) ) {
echo '<div>Country: '  . $value6 . '</div>';
}

}

add_action( 'woocommerce_after_shop_loop_item', 'fields', 10 );

How can I optimize/shorten this code? There might be even more custom fields in the future to be added, so there must be a way to clean up this code?

EDIT to clarify.

Ad

Answer

I would recommend to solve the problem in this way:

  • Create an array of fields
  • Create a loop
  • Use special variables $label and $value for decreasing code line length
  • Use printf to control and format values to display
  • Escape with esc_html to avoid conflicting field value and HTML code.

The code snippet:

global $product;

$fields = [
    [ 'label' => 'Storage', 'name' => 'storage' ],
    [ 'label' => 'Delivery', 'name' => 'delivery_date' ],
    [ 'label' => "Manufacturer's product number", 'name' => 'mpn' ],
    [ 'label' => 'Color', 'name' => 'color' ],
    [ 'label' => 'Sizes', 'name' => 'sizes_available' ],
    [ 'label' => 'Country', 'name' => 'country_of_origin' ],
];

foreach ( $fields as $field ) {
    $label = $field['label'];
    $value = get_post_meta( $product->get_id(), $field['name'], true );

    printf( '<div>%s: %s</div>', esc_html( $label ), esc_html( $value ) );
}
Ad
source: stackoverflow.com
Ad