Include dimension letters L/W/H to WooCommerce formatted product dimensions output

前端 未结 3 2088
盖世英雄少女心
盖世英雄少女心 2021-01-06 23:40

I\'m trying to modify dimensions output that everywhere where get_dimensions() is called instead of default it would include letter of dimensio

相关标签:
3条回答
  • 2021-01-06 23:53

    Updated: You can't override get_dimensions() WC_Product method.

    But you can use woocommerce_format_dimensions filter hook located in wc_format_dimensions() function, to add custom labels to each dimension product attribute, this way (just as you want):

    add_filter( 'woocommerce_format_dimensions', 'custom_formated_product_dimentions', 10, 2 );
    function custom_formated_product_dimentions( $dimension_string, $dimensions ){
        if ( empty( $dimension_string ) )
            return __( 'N/A', 'woocommerce' );
    
        $dimensions = array_filter( array_map( 'wc_format_localized_decimal', $dimensions ) );
        $label_with_dimensions = []; // Initialising
    
        // Loop Though dimensions array
        foreach( $dimensions as $key => $dimention )
            $label_with_dimensions[$key] = strtoupper( substr($key, 0, 1) ) . ' ' . $dimention;
    
        return implode( ' x ',  $label_with_dimensions) . ' ' . get_option( 'woocommerce_dimension_unit' );
    }
    

    Code goes in functions.php file of your active child theme (or theme) or also in any plugin file.

    This code is tested on WooCommerce versions 3+ and works

    0 讨论(0)
  • 2021-01-06 23:58

    I have addEd code to the functions.php file of your active child theme and now it’s working fine:

    add_filter( 'woocommerce_format_dimensions', 'custom_formated_product_dimentions', 10, 2 );
    function custom_formated_product_dimentions( $dimension_string, $dimensions ){
        if ( empty( $dimension_string ) )
            return __( 'N/A', 'woocommerce' );
    
        $dimensions = array_filter( array_map( 'wc_format_localized_decimal', $dimensions ) );
        $label_with_dimensions = []; // Initialising
    
        // Loop Though dimensions array
        foreach( $dimensions as $key => $dimention )
            $label_with_dimensions[$key] = strtoupper( substr($key, 0, 1) ) . ' ' . $dimention;
    
        return implode( ' x ',  $label_with_dimensions) . ' ' . get_option( 'woocommerce_dimension_unit' );
    }
    
    0 讨论(0)
  • 2021-01-07 00:08
    $dimensions = $product->get_dimensions();
    
    if ( !empty( $dimensions) ) {
    
    echo 'Height: ' . $product->get_height() . get_option( 'woocommerce_dimension_unit' );
    
    echo 'Width: ' . $product->get_width() . get_option( 'woocommerce_dimension_unit' );
    
    echo 'Length: ' . $product->get_length() . get_option( 'woocommerce_dimension_unit' );
    
    }
    
    0 讨论(0)
提交回复
热议问题