Làm gì để tạo custom fields cho woocommerce trong chi tiết sản phẩm

Let’s dive into the code then. The WooCommerce API allows us to leverage built-in functions that add all sorts of input fields into the product area. Specifically, you can add six different types of inputs:

  • Text fields
  • Select boxes
  • Checkboxes
  • Radio buttons
  • Textareas
  • Hidden fields

Each of those fields can be added to the regular product tabs of WooCommerce multiple times or in any combination you choose. Those tabs are:

  • General
  • Inventory
  • Shipping
  • Linked Products
  • Attributes
  • Variations
  • Advanced

Any of these tabs come with specific hooks we can use to add our custom fields to that tab. I’ll outline those hooks in more detail soon, but first I want to point out that not all tabs show for each type of product. For example, the “Variations” tab is not showing for “Simple” product types, and the “Shipping” tab is missing if your product is “External”.

You can use a number of hooks to add your fields to any of these tabs:

General Tab

Inventory Tab

Shipping Tab

Linked Products Tab

Attributes Tab

Variations Tab

Advanced Tab

You can find the appropriate hook to use by browsing through the HTML files inside the woocommerce/includes/admin/views folder. Those files make up the meta boxes you’re seeing in the admin interface when editing your products.

In our example, we’ll use the woocommerce_product_options_sku hook to add a field for a second SKU right below the existing SKU field. To do that, we’ll implement functions provided by the WooCommerce API.

Each function takes an array of arguments, which I outlined in the following gists. You can copy and paste each of these directly to your theme’s functions.php file (be sure to use a child theme).

Adding a text field:

Adding a textarea:

Adding a select box:

Adding radio buttons:

Adding a checkbox:

Adding a hidden field:

You can probably guess by now that we’ll use the text field to store our custom SKU. To do that, we’ll implement the following function into the child theme’s functions.php:

function jk_add_custom_sku() {
$args = array(
'label' => __( 'Custom SKU', 'woocommerce' ),
'placeholder' => __( 'Enter custom SKU here', 'woocommerce' ),
'id' => 'jk_sku',
'desc_tip' => true,
'description' => __( 'This SKU is for internal use only.', 'woocommerce' ),
woocommerce_wp_text_input( $args );
add_action( 'woocommerce_product_options_sku', 'jk_add_custom_sku' );

By using this code snippet, you’ll see the custom SKU field in the “Inventory” tab right below the original SKU field. Feel free to adapt the label and description as needed. Be careful when editing the ‘jk_sku‘ ID though, as the saving and display functions depend on that ID and would also need to be adjusted.

Saving the Custom Meta Field

After we add the field for the custom SKU, we need to tell WooCommerce what to do with it when the product is saved. By itself, the above code will do nothing and won’t save the value. That’s obviously not what we want, so let us extend that code and add the saving function.

To do that, we’ll leverage the woocommerce_process_product_meta hook. With the following function, your WooCommerce store will save the new custom SKU field when you save the product:

function jk_save_custom_sku( $post_id ) {
// grab the custom SKU from $_POST
$custom_sku = isset( $_POST[ 'jk_sku' ] ) ? sanitize_text_field( $_POST[ 'jk_sku' ] ) : '';
// grab the product
$product = wc_get_product( $post_id );
// save the custom SKU using WooCommerce built-in functions
$product->update_meta_data( 'jk_sku', $custom_sku );
add_action( 'woocommerce_process_product_meta', 'jk_save_custom_sku' );

Here’s a gist containing both code snippets. You can add the code to your functions.php file directly.

Let me explain the function starting with its trigger point, the hook woocommerce_process_product_meta. It hooks into the WC_Meta_Box_Product_Data::save function, which lets us update product meta fields without calling the regular “add_post_meta” or “update_post_meta” functions. I prefer this approach over using the regular functions to manipulate meta fields, as we ensure that all product data gets processed properly when saving our custom field.

Secure Data Processing and Data Sanitization

Since we, as the developers, cannot expect to know how the user will use this new field, or how good the website will be managed in the future (e.g. keeping a site updated or enforcing strong passwords), we need to be careful about what we store in this field.

To ensure that our function only stores valid data, we’re running the field’s value through sanitize_text_field before adding it to the database.

Accessing Custom Meta Fields in the Frontend or in Mails

Now that we’ve successfully implemented the backend functionality of the custom SKU field, let’s make use of it in the daily business of running the eCommerce shop. In our example, we’ll use the custom SKU and display it in the “new order” notification emails that are sent to the admin of the shop. This will help the shop owner forward orders to the dropshipping vendor and will save a massive amount of time, compared to managing some sort of spreadsheet, mapping product names to the SKU of the vendor.

To add the custom SKU in the frontend, we’ll leverage WooCommerce’s powerful templating system. First, we copy the file email-order-items.php from wp-content/plugins/woocommerce/emails/ to wp-content/themes/your-child-theme/woocommerce/emails. If that folder does not exist in your child theme, you have to create it through FTP/SFTP.

The ability to override email templates (as well as other templates like the product detail page) is one of the big benefits of using WooCommerce. By simply copying the file containing the template for the order item list in emails to the themes folder, you can use your own styling and contents. Just be aware that future WooCommerce updates might require you to update your custom templates, too.

After copying the template file, open it in an editor of your choice (I’m just making the move from PHPStorm to VS Code). You’ll see the template showing a table structure with the body <tr> elements representing each order position. It’s in that context we need to load the custom SKU for each product in order to display it.

Luckily for us, WooCommerce shows the SKU only in admin emails by default, so we don’t need to handle that ourselves. To display the custom field, we’ll use the regular get_post_meta function:

// load the custom SKU
$custom_sku = get_post_meta( $product->get_id(), 'jk_sku', true );
if ( is_string( $custom_sku ) ) { // only show the custom SKU
// if it's set
// change this line if needed
echo "<br>" . wp_kses_post( "Custom SKU: $custom_sku" );

Trả lời

Mời bạn điền thông tin vào ô dưới đây hoặc kích vào một biểu tượng để đăng nhập:

WordPress.com Logo

Bạn đang bình luận bằng tài khoản WordPress.com Đăng xuất /  Thay đổi )

Google photo

Bạn đang bình luận bằng tài khoản Google Đăng xuất /  Thay đổi )

Twitter picture

Bạn đang bình luận bằng tài khoản Twitter Đăng xuất /  Thay đổi )

Facebook photo

Bạn đang bình luận bằng tài khoản Facebook Đăng xuất /  Thay đổi )

Connecting to %s