Add a drop down to product edit pages in product data “General” settings tab

…衆ロ難τιáo~ 提交于 2019-12-04 17:07:06

There is some errors and mistakes so I have revisited a little bit your code. Now you will have to replace woocommerce_wp_text_input() by woocommerce_wp_select() to get a select field instead, this way:

// Enabling and Displaying Fields in backend
add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' );
function woo_add_custom_general_fields() {

    echo '<div class="options_group">';

    woocommerce_wp_select( array( // Text Field type
        'id'          => '_Stan',
        'label'       => __( 'Stan', 'woocommerce' ),
        'description' => __( 'Podaj stan plyty.', 'woocommerce' ),
        'desc_tip'    => true,
        'options'     => array(
            ''        => __( 'Select product condition', 'woocommerce' ),
            'Nowa'    => __('Nowa', 'woocommerce' ),
            'Uzywana' => __('Uzywana', 'woocommerce' ),
        )
    ) );

    echo '</div>';
}

// Save Fields values to database when submitted (Backend)
add_action( 'woocommerce_process_product_meta', 'woo_save_custom_general_fields', 30, 1 );
function woo_save_custom_general_fields( $post_id ){

    // Saving "Conditions" field key/value
    $posted_field_value = $_POST['_Stan'];
    if( ! empty( $posted_field_value ) )
        update_post_meta( $post_id, '_Stan', esc_attr( $posted_field_value ) );


}

// Display In front end
add_action( 'woocommerce_product_meta_start', 'woo_display_custom_general_fields_values', 50 );
function woo_display_custom_general_fields_values() {
    global $product;

    // compatibility with WC +3
    $product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id;

    echo '<span class="stan">Stan: ' . get_post_meta( $product_id, '_Stan', true ) . '</span>';
}

Code goes in function.php file of the active child theme (or active theme).

Tested and works.

Is better to avoid capitals in meta keys and they should start with an underscore.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!