0

I have custom field added to product posts. This is dropdown field and displaying on front end it pulls the option value which is not display friendly, for example select option value is "like_new" with label is "Like New" Is there a way to get Like New displayed instead of like_new?

Here is code for the field, I'm using standard "get_post_meta"

woocommerce_wp_select(
        array(
            'id'      => '_condition',
            'label'   => __( 'Condition', 'woocommerce' ),
            'desc_tip' => 'true',
            'description' => __( 'Part Condition.', 'woocommerce' ),
            'options' => array(
                'new'   => __( 'New', 'woocommerce' ),
                'like_new'   => __( 'New other (see description) ', 'woocommerce' ),
                'remanufactured'   => __( 'Remanufactured', 'woocommerce' ),
                'used' => __( 'Used', 'woocommerce' )
                )
        )
    );

1 Answer 1

1

You can set the keys of the array to be user-friendly, but more appropriate would be to define the options array in a function, and then use that function in both the backend and frontend (untested):

Array

function product_condition_array() {
    return array(
        'new'            => __( 'New', 'woocommerce' ),
        'like_new'       => __( 'New other (see description) ', 'woocommerce' ),
        'remanufactured' => __( 'Remanufactured', 'woocommerce' ),
        'used'           => __( 'Used', 'woocommerce' ),
    );
}

Backend

woocommerce_wp_select(
    array(
        'id'          => '_condition',
        'label'       => __( 'Condition', 'woocommerce' ),
        'desc_tip'    => true,
        'description' => __( 'Part Condition.', 'woocommerce' ),
        'options'     => product_condition_array(),
    )
);

Frontend

$condition = get_post_meta( … );
$conditions = product_condition_array();
$condition_display = __( 'Unknown', 'woocommerce' );

if ( array_key_exists( $condition, $conditions ) ) {
    $condition_display = $conditions[ $condition ];
}

echo esc_html( $condition_display );

This has the benefit of a single location used by both backend and frontend, so changes are reflected immediately in both locations, simplifying future changes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.