简体   繁体   中英

In WooCommerce product options edit page display a custom field before the SKU

So I've got the following function to add a barcode field in the Product Inventory tab. However this field is being added after all the other content, and I would like to have this before the SKU code.

function add_barcode(){
    global $woocommerce,$post;
    woocommerce_wp_text_input(
        array(
            'id'          => '_barcode',
            'label'       => __('Barcode','woocommerce'),
            'placeholder' => 'Scan Barcode',
            'desc_tip'    => 'true',
            'description' => __('Scan barcode.','woocommerce')
        ));
}
add_action('woocommerce_product_options_inventory_product_data','add_barcode');

Is there anyway to place the function/field before the SKU aka before the actual hook, like something in terms of woocommerce_before_product_options_inventory_product_data?

Thanks for any suggestions in advance.

IS NOT POSSIBLE TO PLACE ANY CUSTOM FIELD BEFORE THE SKU

You can take a look to html-product-data-inventory.php source code file which displays product inventory fields.

But you can display your 'Barcode' custom field just after the SKU field (for example)

For that you have to hook your custom function in woocommerce_product_options_sku action hook instead. There is also some missing things in your code to display a saved value.

And finally you need another function to save that value when product is saved or updated.

Here is that complete code:

add_action('woocommerce_product_options_sku','add_barcode_custom_field' );
function add_barcode_custom_field(){
    woocommerce_wp_text_input( array(
        'id'          => '_barcode',
        'label'       => __('Barcode','woocommerce'),
        'placeholder' => 'Scan Barcode',
        'desc_tip'    => 'true',
        'description' => __('Scan barcode.','woocommerce')
    ) ); 
}

add_action( 'woocommerce_process_product_meta', 'save_barcode_custom_field', 10, 1 );
function save_barcode_custom_field( $post_id ){
    if( isset($_POST['_barcode']) )
        update_post_meta( $post_id, '_barcode', esc_attr( $_POST['_barcode'] ) );
}

This code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works for WooCommerce version 2.6+ and 3.0+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM