Created
May 25, 2023 11:17
-
-
Save lucasstark/8cff45f68fed98928d79eaacaf9f35ca to your computer and use it in GitHub Desktop.
Add Sample Custom Product Field for Testing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Product_Custom_Field { | |
public function __construct() { | |
add_action( 'woocommerce_before_add_to_cart_button', array( $this, 'display_custom_field' ) ); | |
add_filter( 'woocommerce_add_cart_item_data', array( $this, 'add_cart_item_data' ), 10, 2 ); | |
add_filter( 'woocommerce_get_item_data', array( $this, 'get_item_data' ), 10, 2 ); | |
add_action( 'woocommerce_checkout_create_order_line_item', array( $this, 'checkout_create_order_line_item' ), 10, 4 ); | |
} | |
public function display_custom_field() { | |
echo '<div class="custom-field-wrapper">'; | |
echo '<label for="custom_field">Custom Field:</label>'; | |
echo '<input type="text" id="custom_field" name="custom_field" />'; | |
echo '</div>'; | |
} | |
public function add_cart_item_data( $cart_item_data, $product_id ) { | |
if ( isset( $_POST['custom_field'] ) ) { | |
$cart_item_data['custom_field'] = sanitize_text_field( $_POST['custom_field'] ); | |
} | |
return $cart_item_data; | |
} | |
public function get_item_data( $item_data, $cart_item_data ) { | |
if ( isset( $cart_item_data['custom_field'] ) ) { | |
$item_data[] = array( | |
'key' => 'Custom Field', | |
'value' => $cart_item_data['custom_field'], | |
'display' => '', | |
); | |
} | |
return $item_data; | |
} | |
public function checkout_create_order_line_item( $item, $cart_item_key, $values, $order ) { | |
if ( isset( $values['custom_field'] ) ) { | |
$item->add_meta_data( 'Custom Field', $values['custom_field'], true ); | |
} | |
} | |
} | |
new Product_Custom_Field(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment