I have some custom code that creates a shortcode in WordPress/Woocommerce that I use to display the product dimensions (Length, Width, Height) – the output works fine however I would like to change the label for ‘Length‘ to read ‘Depth‘ (front end only is fine) and re-order the output to display as Height, Width, Depth (in that order)
Here is my code to create the shortcode – however, I am unsure what I need to do to change the output label & to re-order them.
add_shortcode( 'product_taxonomies', 'product_taxonomies_shortcode' );
function product_taxonomies_shortcode( $atts ){
// Shortcode Attributes
$atts = shortcode_atts( array(
'id' => '',
), $atts, 'product_taxonomies' );
$product_id = ! empty($atts['id']) ? $atts['id'] : 0;
if( $product_id > 0 ) {
$product = wc_get_product( $product_id );
} else {
global $product;
}
if( ! is_a($product, 'WC_Product' ) ) {
$product = wc_get_product( get_the_id() );
}
if ( is_a($product, 'WC_Product' ) ) {
ob_start();
// Weight
if ( $product->has_weight() ) {
$weight_unit = get_option('woocommerce_weight_unit');
$weight_html = '<strong>'.__("Weight").':</strong> ' . $value . $weight_unit;
echo '<div class="dimensions">' . $weight_html . '</div>';
}
// Dimensions
if ( $product->has_dimensions() ) {
$dimension_unit = get_option('woocommerce_dimension_unit');
$dimensions = array();
foreach( $product->get_dimensions( false ) as $key => $value ) {
if( ! empty($value) )
$dimensions[] = '<strong>'.ucfirst($key).':</strong> ' . $value . $dimension_unit;
}
echo '<div class="dimensions">' . implode('<br>', $dimensions) . '</div>';
}
return ob_get_clean();
}
}
3
Answers
I think i've worked it out doing it another way
This seems to work and display correctly...
Problem-space
First, let’s identify the code-range where you need to perform your changes:
Perform the changes
Explanation
$key
, otherwise use the$key
, any replacement being done on the representation levelPotential problem
I assumed some concrete key values. If my understanding of them is wrong, then some incorrect values might cause troubles. If that’s the case, let’s discuss the situation you might arrive to.
I know it’s not directly what you were asking for, maybe even off topic on a developer forum. But I wanted to provide a second option: a plugin that allows you to alter strings on your site without editing WordPress core.
I guess there is a lot of those plugins out there, but one I like is one called Say What
Best of luck!