Add custom field as item meta data on the Order - wordpress

I have added a custom field to the woocommerce products, it is working well with the following code. But my problem is how to add it to the cart_item_data
// Display Text in Admin Panel
add_action('woocommerce_product_options_general_product_data', 'product_custom_text_field');
function product_custom_text_field()
{
// Custom Product Text Field ( para Tex Area -> woocommerce_wp_textarea_input )
woocommerce_wp_text_input(
array(
'id' => '_optional_text_field',
'label' => __('Customize title', 'woocommerce'),
'placeholder' => '',
'desc_tip' => 'true',
'description' => __('Customizable title for the field that the user must fill out.', 'woocommerce')
)
);
}
Save Fields
add_action('woocommerce_process_product_meta', 'product_custom_text_field_save');
function product_custom_text_field_save($post_id)
{
if (!empty($_POST['_optional_text_field'])) {
update_post_meta($post_id, '_optional_text_field', esc_attr($_POST['_optional_text_field']));
}
}
Display The Text in Product Page
add_action('woocommerce_single_variation', 'display_text_field');
function display_text_field()
{
global $post;
if (get_post_meta($post->ID, '_optional_text_field', true)) {
echo "<div class='titulo-c'><label>";
echo get_post_meta($post->ID, '_optional_text_field', true);
echo "</label></div>";
return;
}
echo __('FREE LOCAL SHIPPING', 'woocommerce');
}
So far it works without problems, now I want to add it to the cart_item_data, with the following code, but it does not work for me.
add_filter( 'woocommerce_add_cart_item_data', 'add_cart_item_data', 25, 2 );
function add_cart_item_data( $cart_item_meta, $product_id ) {
$custom_data = array() ;
$custom_data[ "_optional_text_field"] = isset( $_POST['_optional_text_field'] ) ? sanitize_text_field ( $_POST['_optional_text_field'] ) : "" ;
$cart_item_meta ['custom_data'] = $custom_data ;
return $cart_item_meta;
}
Display custom data on cart and checkout page.
add_filter( 'woocommerce_get_item_data', 'get_item_data' , 25, 2 );
function get_item_data ( $other_data, $cart_item ) {
if ( isset( $cart_item [ 'custom_data' ] ) ) {
$custom_data = $cart_item [ 'custom_data' ];
$other_data[] = array( 'name' => 'Title',
'display' => $custom_data['_optional_text_field'] );
}
return $other_data;
}
As a result, it only appears to me: Title: ________
I will appreciate any suggestions to make my code work.

Make the following changes to your code as below, this should work.
/**
* Add data to cart item
*/
add_filter( 'woocommerce_add_cart_item_data', 'add_cart_item_data', 25, 2 );
function add_cart_item_data( $cart_item_meta, $product_id ) {
global $woocommerce;
$mytitle_form_data = get_post_meta($product_id, '_optional_text_field', true);
$custom_data = array() ;
$custom_data[ "_optional_text_field"] = $mytitle_form_data;
$cart_item_meta ['custom_data'] = $custom_data ;
return $cart_item_meta;
}

Related

Save multiple datas in order WooCommerce

I have two customs fields in my product (image and texte), I all ready show it in the cart but when the order is complete, i can't find how can I show both in the admin order (I can show one of two ^^)
Here is the code :
// Add custom fields data as the cart item custom data
add_filter( 'woocommerce_add_cart_item_data', 'add_custom_fields_data_as_custom_cart_item_data', 10, 2 );
function add_custom_fields_data_as_custom_cart_item_data($cart_item, $product_id){
if( isset($_FILES['image']) && !empty($_FILES['image']) && !empty($_POST['nom_pp']) ) {
$upload = wp_upload_bits( $_FILES['image']['name'], null, file_get_contents( $_FILES['image']['tmp_name'] ) );
$filetype = wp_check_filetype( basename( $upload['file'] ), null );
$upload_dir = wp_upload_dir();
$upl_base_url = is_ssl() ? str_replace('http://', 'https://', $upload_dir['baseurl']) : $upload_dir['baseurl'];
$base_name = basename( $upload['file'] );
$cart_item['file_upload'] = array(
'guid' => $upl_base_url .'/'. _wp_relative_upload_path( $upload['file'] ), // Url
'file_type' => $filetype['type'], // File type
'file_name' => $base_name, // File name
'title' => ucfirst( preg_replace('/\.[^.]+$/', '', $base_name ) ), // Title
);
$cart_item['nom_pp'] = $_POST['nom_pp'];
$cart_item['unique_key'] = md5( microtime().rand() ); // Avoid merging items
}
return $cart_item;
}
// Display custom cart item data in cart (optional)
add_filter('woocommerce_get_item_data', 'njengah_custom_item_data', 10, 2);
function njengah_custom_item_data($cart_item_data, $cart_item) {
if ( isset($cart_item['file_upload']['title']) ){
$cart_item_data[] = array(
'name' => __( 'Mon image ', 'woocommerce' ),
'value' => str_pad($cart_item['file_upload']['title'], 16, 'X', STR_PAD_LEFT) . '…',
);
}
if ( isset($cart_item['nom_pp']) ){
$cart_item_data[] = array(
'name' => __( 'Nom du papier peint ', 'woocommerce' ),
'value' => $cart_item['nom_pp'],
);
}
return $cart_item_data;
}
// Save Image data as order item meta data
add_action( 'woocommerce_checkout_create_order_line_item', 'njengah_field_update_order_item_meta', 20, 4 );
function njengah_field_update_order_item_meta( $item, $cart_item_key, $values, $order ) {
if ( isset($values['file_upload']) && isset($values['nom_pp']) ){
$item->update_meta_data($item, '_img_file', $values['file_upload']);
$item->update_meta_data($item, '_nom_pp', $values['nom_pp']);
}
}
// Admin orders: Display a linked button + the link of the image file
add_action( 'woocommerce_after_order_itemmeta', 'njengah_image_link_after_order_itemmeta', 10, 3 );
function njengah_image_link_after_order_itemmeta( $item_id, $item, $product ) {
// Only in backend for order line items (avoiding errors)
if( is_admin() && $item->is_type('line_item') && $file_data = $item->get_meta('_img_file') && $file_data = $item->get_meta('_nom_pp') ){
echo '<p>'.__("Voir l'image") . '</p>'; // Optional
echo '<p><code>'.$file_data['guid'].'</code></p>'; // Optional
echo '<p>'.$file_data['nom_pp'].'</p>'; // Optional
}
}
I think I need to edit the order meta data, but I don't know how can I do it :)

Add custom select field with validation to WooCommerce checkout page if certain products are in cart

I wish to add a custom select field with validation to the WooCommerce checkout page if certain products are in cart.
With my current code I retrieve the value of my custom WooCommerce form field. However, it display "array" at the order page.
I have an select field which have an option of 1 and 0. Upon selection of the select field, i want it to display either 1 or 0 at the order page but im unable to do so.
Please guide me on what should i do with my current codes:
//AMBASSADOR CUSTOM CHECKOUT FIELDS, CONTENT add marketplace for sameday TEST
add_action( 'woocommerce_after_checkout_billing_form', 'aym_custom_checkout_field' );
function aym_custom_checkout_field( $checkout ) {
//Check if Product in Cart
$prod_in_cart_17563 = aym_is_conditional_product_in_cart_17563( 212 );
if ( $prod_in_cart_17563 === true ) {
$domain = 'wocommerce';
$default = 'Y';
woocommerce_form_field( '_my_field_name', array(
'type' => 'select',
'class' => array( 'form-row-wide' ),
'label' => __( 'Market Place - Please Select Y to complete this order' ),
'required' => true,
'options' => array(
'Y' => __('1'),
'N' => __('0')
),'default' => $default),
$checkout->get_value( '_my_field_name' ) );
}
}
//AMBSSADOR BUNDLE add marketplace for same day pa rt 2
function aym_is_conditional_product_in_cart_17563( $product_id ) {
//Check to see if user has product in cart
global $woocommerce;
//flag no product in cart
$prod_in_cart_17563 = false;
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->id === $product_id ) {
//product is in cart!
$prod_in_cart_17563 = true;
}
}
return $prod_in_cart_17563;
}
//process orders in order page
// Custom checkout fields validation
add_action( 'woocommerce_checkout_process', 'custom_checkout_field_process' );
function custom_checkout_field_process() {
if ( isset($_POST['_my_field_name']) && empty($_POST['_my_field_name']) )
wc_add_notice( __( 'Please fill in "My 1st new field".' ), 'error' );
}
// Save custom checkout fields the data to the order
add_action( 'woocommerce_checkout_create_order', 'custom_checkout_field_update_meta', 10, 2 );
function custom_checkout_field_update_meta( $order, $data ){
if( isset($_POST['_my_field_name']) && ! empty($_POST['_my_field_name']) )
$order->update_meta_data( '_my_field_name', sanitize_text_field( $_POST['_my_field_name'] ) );
}
/**
* Update the order meta with field value
**/
add_action('woocommerce_checkout_update_order_meta', 'my_custom_checkout_field_update_order_meta');
function my_custom_checkout_field_update_order_meta( $order_id ) {
if ($_POST['_my_field_name']) update_post_meta( $order_id, 'My Field', esc_attr($_POST['_my_field_name']));
}
// View fields in Edit Order Page
add_action( 'woocommerce_admin_order_data_after_billing_address', 'display_custom_fields_value_admin_order', 10, 1 );
function display_custom_fields_value_admin_order( $order ){
// Display the delivery option
if( $delivery_option = $order->get_meta('_my_field_name') )
echo '<p><strong>'.__('Delivery type').':</strong> ' . $delivery_option . '</p>';
}
// Display field value on the order edit page
add_action( 'woocommerce_admin_order_data_after_billing_address', 'my_custom_checkout_field_display_admin_order_meta', 10, 1 );
function my_custom_checkout_field_display_admin_order_meta( $order ) {
if( $selectoption = $order->get_meta('_my_field_name') ) {
//$value = wc_get_hearaboutus_options()[$selectoptions];
$meta= get_post_meta( $post->ID, $selectoption, true );
$myvalues = unserialize( $meta );
echo '<p><strong>'.__('Market_Place').':</strong> ' . $myvalues . '</p>';
}
}
I have partly rewritten / modified your code with some (extra) features
The ability to check for multiple product IDs in the shopping cart
The custom field is only added if a certain product id is in the shopping cart
The possibility to check out if the custom field is not present (product ID is NOT in cart)
No possibility to checkout as long as the value 'Y' is not selected from the custom select menu (Product ID is IN cart)
Explanation via comment tags added in the code
// Add custom 'select' field after checkout billing form (if product ID is in cart)
function action_woocommerce_after_checkout_billing_form( $checkout ) {
// Check if Product in Cart
// Multiple product IDs can be entered, separated by a comma
$product_in_cart = is_product_in_cart( array( 212, 30, 815 ) );
// True
if ( $product_in_cart ) {
$domain = 'woocommerce';
$default = 'Y';
woocommerce_form_field( '_my_field_name', array(
'type' => 'select',
'class' => array( 'form-row-wide' ),
'label' => __( 'Market Place - Please Select Y to complete this order', $domain ),
'required' => true,
'options' => array(
'Y' => __( 'Y', $domain ),
'N' => __( 'N', $domain ),
),
'default' => $default,
), $checkout->get_value( '_my_field_name' ) );
}
}
add_action( 'woocommerce_after_checkout_billing_form', 'action_woocommerce_after_checkout_billing_form', 10, 1 );
// Function to check if a certain product ID is in cart
function is_product_in_cart( $targeted_ids ) {
// Flag no product in cart
$flag = false;
// WC Cart NOT null
if ( ! is_null( WC()->cart ) ) {
// Loop through cart items
foreach( WC()->cart->get_cart() as $cart_item ) {
// Check cart item for defined product Ids
if ( in_array( $cart_item['product_id'], $targeted_ids ) ) {
// Product is in cart
$flag = true;
// Break loop
break;
}
}
}
return $flag;
}
// Custom checkout 'select' field validation
function action_woocommerce_checkout_process() {
// Isset
if ( isset( $_POST['_my_field_name'] ) ) {
$domain = 'woocommerce';
$my_field_name = $_POST['_my_field_name'];
// Empty
if ( empty ( $my_field_name ) ) {
wc_add_notice( __( 'Please Select Y to complete this order', $domain ), 'error' );
}
// NOT empty but value is 'N'
if ( ! empty ( $my_field_name ) && $my_field_name == 'N' ) {
wc_add_notice( __( 'Please Select Y to complete this order', $domain ), 'error' );
}
}
}
add_action( 'woocommerce_checkout_process', 'action_woocommerce_checkout_process', 10, 0 );
// Save custom checkout 'select' field
function action_woocommerce_checkout_create_order( $order, $data ) {
// Isset
if ( isset( $_POST['_my_field_name'] ) ) {
$my_field_name = $_POST['_my_field_name'];
// NOT empty & equal to 'Y'
if ( ! empty( $my_field_name ) && $my_field_name == 'Y' ) {
$order->update_meta_data( '_my_field_name', sanitize_text_field( $my_field_name ) );
}
}
}
add_action( 'woocommerce_checkout_create_order', 'action_woocommerce_checkout_create_order', 10, 2 );
// Display the custom 'select' field value on admin order pages after billing adress
function action_woocommerce_admin_order_data_after_billing_address( $order ) {
$domain = 'woocommerce';
// Get meta
$my_field_name = $order->get_meta( '_my_field_name' );
// NOT empty
if ( ! empty ( $my_field_name ) ) {
echo '<p><strong>' . __( 'Delivery type', $domain ) . ':</strong> ' . $order->get_meta( '_my_field_name' ) . '</p>';
}
}
add_action( 'woocommerce_admin_order_data_after_billing_address', 'action_woocommerce_admin_order_data_after_billing_address', 10, 1 );
// Display the custom 'select' field value on 'order received' and 'order view' pages (frontend)
function action_woocommerce_order_details_after_order_table( $order ) {
$domain = 'woocommerce';
// Get meta
$my_field_name = $order->get_meta( '_my_field_name' );
// NOT empty
if ( ! empty ( $my_field_name ) ) {
echo '<p><strong>' . __( 'Delivery type', $domain ) . ':</strong> ' . $order->get_meta( '_my_field_name' ) . '</p>';
}
}
add_action( 'woocommerce_order_details_after_order_table', 'action_woocommerce_order_details_after_order_table', 10, 1 );

Save and display product selected custom data in WooCommerce

I use the code, that on the product editing page shows the checkbox "Roast Level". When the manager clicks on this checkbox, a select box appears on the page of a single product, allowing the customer to select "Roast Level".
When selecting and adding a product to the cart, the selected value appears in the cart itself. This value is also shown on the checkout page, on the "Thank You" page, in the order, on the email notification, and on the order editing page in the admin panel.
Here is the code:
// Display Checkbox Field
add_action('woocommerce_product_options_general_product_data', 'roast_custom_field_add');
function roast_custom_field_add() {
global $post;
// Checkbox
woocommerce_wp_checkbox(
array(
'id' => '_roast_checkbox',
'label' => __('Roast Level', 'woocommerce'),
'description' => __('Enable roast level!', 'woocommerce')
)
);
}
// Save Checkbox Field
add_action('woocommerce_process_product_meta', 'roast_custom_field_save');
function roast_custom_field_save($post_id) {
// Custom Product Checkbox Field
$roast_checkbox = isset($_POST['_roast_checkbox']) ? 'yes' : 'no';
update_post_meta($post_id, '_roast_checkbox', esc_attr($roast_checkbox));
}
// Display Select Box
add_action('woocommerce_before_add_to_cart_button', 'add_roast_custom_field', 0);
function add_roast_custom_field() {
global $product;
// If is single product page and have the "roast_checkbox" enabled we display the field
if (is_product() && $product->get_meta('_roast_checkbox') === 'yes') {
echo '<div>';
woocommerce_form_field('roast_custom_options', array(
'type' => 'select',
'class' => array('my-field-class form-row-wide'),
'label' => __('Roast Level'),
'required' => false,
'options' => array(
'' => 'Please select',
'Blue' => 'Blue',
'Rare' => 'Rare',
'Medium Rare' => 'Medium Rare',
'Medium' => 'Medium',
'Medium Well' => 'Medium Well',
'Well Done' => 'Well Done'
)
), '');
echo '</div>';
}
}
// Add as custom cart item data
add_filter('woocommerce_add_cart_item_data', 'add_custom_cart_item_data', 10, 3);
function add_custom_cart_item_data($cart_item_data, $product_id, $variation_id) {
if (isset($_POST['roast_custom_options'])) {
$cart_item_data['roast_option'] = wc_clean($_POST['roast_custom_options']);
}
return $cart_item_data;
}
// Add custom fields values under cart item name in cart
add_filter('woocommerce_cart_item_name', 'roast_custom_field', 10, 3);
function roast_custom_field($item_name, $cart_item, $cart_item_key) {
if (!is_cart())
return $item_name;
if (isset($cart_item['roast_option'])) {
$item_name. = '<br /><div class="my-custom-class"><strong>'.__("Roast Level", "woocommerce").
':</strong> '.$cart_item['roast_option'].
'</div>';
}
return $item_name;
}
// Display roast custom fields values under item name in checkout
add_filter('woocommerce_checkout_cart_item_quantity', 'roast_custom_checkout_cart_item_name', 10, 3);
function roast_custom_checkout_cart_item_name($item_qty, $cart_item, $cart_item_key) {
if (isset($cart_item['roast_option'])) {
$item_qty. = '<br /><div class="my-custom-class"><strong>'.__("Roast Level", "woocommerce").
':</strong> '.$cart_item['roast_option'].
'</div>';
}
return $item_qty;
}
// Save chosen slelect field value to each order item as custom meta data and display it everywhere
add_action('woocommerce_checkout_create_order_line_item', 'save_order_item_product_fitting_color', 10, 4);
function save_order_item_product_fitting_color($item, $cart_item_key, $values, $order) {
if (isset($values['_roast_option'])) {
$key = __('Roast Level', 'woocommerce');
$value = $values['_roast_option'];
$item->update_meta_data($key, $value);
}
}
This code works well in the Storefront theme, but for some reason, it does not work in the theme I bought on Themeforest. Developers can not help, they say that I need to contact the person who wrote this code. And that's why...
I also use code that works in the Storefront and in the purchased theme. Here it is - Show custom fields on the order editing page in WooCommerce
, those. It works great in these two themes.
As I understand it, this is due to the syntax "echo". In the form of "Roast Level" this syntax is, therefore the form is shown. When displaying selected data in the cart or on the checkout page, this syntax is not.
UPDATE
Here is the code that doesn't work without "echo":
// Add custom fields values under cart item name in cart
add_filter('woocommerce_cart_item_name', 'roast_custom_field', 10, 3);
function roast_custom_field($item_name, $cart_item, $cart_item_key) {
if (!is_cart())
return $item_name;
if (isset($cart_item['roast_option'])) {
$item_name. = '<br /><div class="my-custom-class"><strong>'.__("Roast Level", "woocommerce").
':</strong> '.$cart_item['roast_option'].
'</div>';
}
return $item_name;
}
// Display roast custom fields values under item name in checkout
add_filter('woocommerce_checkout_cart_item_quantity', 'roast_custom_checkout_cart_item_name', 10, 3);
function roast_custom_checkout_cart_item_name($item_qty, $cart_item, $cart_item_key) {
if (isset($cart_item['roast_option'])) {
$item_qty. = '<br /><div class="my-custom-class"><strong>'.__("Roast Level", "woocommerce").
':</strong> '.$cart_item['roast_option'].
'</div>';
}
return $item_qty;
}
// Save chosen slelect field value to each order item as custom meta data and display it everywhere
add_action('woocommerce_checkout_create_order_line_item', 'save_order_item_product_fitting_color', 10, 4);
function save_order_item_product_fitting_color($item, $cart_item_key, $values, $order) {
if (isset($values['_roast_option'])) {
$key = __('Roast Level', 'woocommerce');
$value = $values['_roast_option'];
$item->update_meta_data($key, $value);
}
}
I ask to change my code so that it has the syntax "echo", so that the selected data is output using "echo". I will be glad for your help!
Following Code should Work
/*---------------------------------------------------------------
*Display Select Box
---------------------------------------------------------------*/
add_action( 'woocommerce_before_add_to_cart_button', 'add_roast_custom_field', 0 );
function add_roast_custom_field() {
global $product;
// If is single product page and have the "roast_checkbox" enabled we display the field
if ( is_product() && $product->get_meta( '_roast_checkbox' ) === 'yes' ) {
echo '<div class="roast_select">';
$select = woocommerce_form_field( 'roast_custom_options', array(
'type' => 'select',
'class' => array('my-field-class form-row-wide'),
'label' => __('Roast Level'),
'required' => false,
'return' => false,
'options' => array(
'' => 'Please select',
'Blue' => 'Blue',
'Rare' => 'Rare',
'Medium Rare' => 'Medium Rare',
'Medium' => 'Medium',
'Medium Well' => 'Medium Well',
'Well Done' => 'Well Done'
)
), '' );
echo $select;
echo '</div>';
}
}
/*---------------------------------------------------------------
* Add as custom cart item data
---------------------------------------------------------------*/
add_filter( 'woocommerce_add_cart_item_data', 'add_custom_cart_item_data', 10, 21 );
function add_custom_cart_item_data($cart_item_data, $product_id, $variation_id ){
if( isset( $_POST['roast_custom_options'] ) ) {
$cart_item_data['roast_option'] = wc_clean( $_POST['roast_custom_options'] );
}
return $cart_item_data;
}
/*---------------------------------------------------------------
* Add custom fields values under cart item name in cart
---------------------------------------------------------------*/
add_filter( 'woocommerce_cart_item_name', 'roast_custom_field', 10, 21 );
function roast_custom_field( $item_name, $cart_item, $cart_item_key ) {
if( ! is_cart() )
return $item_name;
if( isset($cart_item['roast_option']) ) {
$item_name .= '<br /><div class="my-custom-class"><strong>' . __("Roast Level", "woocommerce") . ':</strong> ' . $cart_item['roast_option'] . '</div>';
}
return $item_name;
}
/*---------------------------------------------------------------
* Display roast custom fields values under item name in checkout
---------------------------------------------------------------*/
add_filter( 'woocommerce_checkout_cart_item_quantity', 'roast_custom_checkout_cart_item_name', 10, 21 );
function roast_custom_checkout_cart_item_name( $item_qty, $cart_item, $cart_item_key ) {
if( isset($cart_item['roast_option']) ) {
$item_qty .= '<br /><div class="my-custom-class"><strong>' . __("Roast Level", "woocommerce") . ':</strong> ' . $cart_item['roast_option'] . 'гр.</div>';
}
return $item_qty;
}
/*---------------------------------------------------------------
* Save chosen slelect field value to each order item as custom meta data and display it everywhere
---------------------------------------------------------------*/
add_action('woocommerce_checkout_create_order_line_item', 'save_order_item_product_fitting_color', 10, 21 );
function save_order_item_product_fitting_color( $item, $cart_item_key, $values, $order ) {
if( isset($values['roast_option']) ) {
$key = __('Roast Level', 'woocommerce');
$value = $values['roast_option'];
$item->update_meta_data( $key, $value ,$item->get_id());
}
}
/*--------------------------------------------------------------------
The following code played the important role in your theme
Your add to cart form takes the values when user clicks on add to cart button
After it ajax runs and takes the values from the butoons custom attribute
like data-product_id, data-roast_custom_options So i have added it using jquery
check the code and your site. All the codesprovided by me working now.
--------------------------------------------------------------------*/
add_action('wp_footer','add_footer_script');
function add_footer_script(){
?>
<script>
jQuery('#roast_custom_options').on('change',function(){
var roast_level = jQuery(this).val();
/*console.log(roast_level); */
var button = jQuery(this).closest('form').find('.add_to_cart_button'); console.log(button);
jQuery(button).attr('data-roast_custom_options',roast_level);
});
</script>
<?php
}

Display custom fields in variations product page WooCommerce

I've created two custom fields in variations with the following code (Thanks Remi Corso):
functions.php
Add Variation Settings
add_action( 'woocommerce_product_after_variable_attributes', 'variation_settings_fields', 10, 3 );
Save Variation Settings
add_action( 'woocommerce_save_product_variation', 'save_variation_settings_fields', 10, 2 );
Create new fields for variations
function variation_settings_fields( $loop, $variation_data, $variation ) {
woocommerce_wp_text_input(
array(
'id' => '_pdf_ficha_tecnica[' . $variation->ID . ']',
'label' => __( 'PDF FICHA TÉCNICA', 'woocommerce' ),
'placeholder' => 'http://',
'desc_tip' => 'true',
'description' => __( 'aqui', 'woocommerce' ),
'value' => get_post_meta( $variation->ID, '_pdf_ficha_tecnica', true )
)
);
woocommerce_wp_text_input(
array(
'id' => '_pdf_ficha_caracteristicas[' . $variation->ID . ']',
'label' => __( 'PDF FICHA CARACTERÍSTICAS', 'woocommerce' ),
'placeholder' => 'http://',
'desc_tip' => 'true',
'description' => __( 'aqui', 'woocommerce' ),
'value' => get_post_meta( $variation->ID, '_pdf_ficha_caracteristicas', true )
)
);
}
Save new fields for variations
function save_variation_settings_fields( $post_id ) {
$text_field = $_POST['_pdf_ficha_tecnica'][ $post_id ];
if( ! empty( $text_field ) ) {
update_post_meta( $post_id, '_pdf_ficha_tecnica', esc_attr( $text_field ) );
}
$text_field = $_POST['_pdf_ficha_caracteristicas'][ $post_id ];
if( ! empty( $text_field ) ) {
update_post_meta( $post_id, '_pdf_ficha_caracteristicas', esc_attr( $text_field ) );
}
}
These custom fields store URLs and will be displayed as links <a href>. I looking to display these fields but I'm having a lot of trouble finding the right solution.
Can anyone guide me?
Should I focus on file "variable.php"?
And the JS?
Or can I render the fields by hooks?
The following code I created works perfectly. I am new to JS and I'm sure can be improved. I hope that will be helpful. To create Custom Fields reads the post of REMI.
Explanation: With "WC_Product Variable" object can display the Custom Fields of product variation,
To display these fields I used jquery, the contents of the span "sku" will be our reference as shown on the product page. This code in the "variations.php" file.
<?php
// With "WC_Product Variable" object I get the Custom Fields variations.
$product_id = $product->id;
$variation = new WC_Product_Variable( $product_id );
$arrvariations = $variation->get_children ();
// With foreach construct the div that will contain the Custom Fields
foreach ($arrvariations as $varid) {
$cfvalone = get_post_meta( $varid, '_custom_field_one', true );
$cfvaltwo = get_post_meta( $varid, '_custom_field_two', true );
// Check the Custom Fields are not empty
if (!empty($cfvalone) or !empty($cfvaltwo) ) {
$cfonecont = get_post_meta( $varid, '_custom_field_one', true );
$cftwocont = get_post_meta( $varid, '_custom_field_two', true );
$varsku = get_post_meta( $varid, '_sku', true );
// Built the DIV and embed SKU of the variation to be processed later by JS.
?>
<div class="varskudiv" data-varskudiv="<? echo $varsku;?>" style="display:none;">
<?php if (!empty($cfonecont)) {?>
CUSTOM FIELD ONE
<?php } ?>
<?php if (!empty($cftwocont)) {?>
CUSTOM FIELD TWO
<?php } ?>
</div>
<? }}?>
<br/>
<script>
jQuery(document).ready(function( $ ) {
// As we will take the contents of SPAN "sku" to create the JS
//we must consider that this SPAN is complete once the screen is loaded.
$(window).bind("load", function() {
woosku = $(".sku").text();
// Now we map the DIV we created "varskudiv" and load those values in an ARRAY
wooarrsku = $('div.varskudiv').map(function(){
return $(this).data('varskudiv');
}).get();
// Now we make loop, if the values match show the DIV.
var indexsku;
for (indexsku = 0; indexsku < wooarrsku.length; indexsku++) {
if (woosku == wooarrsku[indexsku]) {
$('.varskudiv[data-varskudiv="'+ woosku +'"]').css( "display", "inline-block" );
}
}
});
// Once loaded the screen, if the SPAN "sku" changes, start the process again and hide the previous DIV displayed.
$('.sku').bind("DOMSubtreeModified",function(){
woosku = $(".sku").text();
wooarrsku = $('div.varskudiv').map(function(){
return $(this).data('varskudiv');
}).get();
var indexsku;
for (indexsku = 0; indexsku < wooarrsku.length; indexsku++) {
if (woosku == wooarrsku[indexsku]) {
$('.varskudiv[data-varskudiv="'+ woosku +'"]').css( "display", "inline-block" );
}
else {$('.varskudiv[data-varskudiv="'+ wooarrsku[indexsku] +'"]').css( "display", "none" );
}
}
});
});
</script>

Delete metadata in WP admin custom columns

I want to delete metadata from the admin panel of my custom post in WP. I created my custom column and display the desired metadata inside but when I try to create a button to delete the metadata nothing happens.
My code tries to delete the metadata and user post with foreach.
Any help would be much appreciated.
code Done! 05/05/15:
Change Admin Columns:
add_action( "manage_favor_posts_columns", "change_columns" );
function change_columns( $cols ) {
$cols = array(
'cb' => '<input type="checkbox" />',
'title' => __( 'Título del favor', 'trans' ),
'usuarios_registrados' => __('Usuarios Registrados', 'trans'),
'date' => __( 'Fecha publicación', 'trans' ),
);
return $cols;
}
add_action( "manage_posts_custom_column", "custom_columns_phi", 10, 2 );
Add output metas and delete link in columns:
function custom_columns_phi( $column, $post_id ) {
switch ( $column ) {
case "usuarios_registrados":
$favor_post_meta_datos = get_post_meta ($post_id, 'usuarios_favores');
foreach($favor_post_meta_datos as $term_post){
$user_phi_name = get_userdata ($term_post);
?>
<li><?echo $user_phi_name->first_name;?> | Cancelar</li>
<?
}
break;
}
}
Add init function in admin screen:
function phi_admin_preload_get () {
if ( isset($_GET['value_phi_user'] )) {
$phi_get_post = $_GET['value_phi_post'];
$phi_get_user = $_GET['value_phi_user'];
delete_post_meta ($phi_get_post, 'usuarios_favores', $phi_get_user);
delete_user_meta ($phi_get_user, 'favores', $phi_get_post );
}
}
add_action ('admin_init', 'phi_admin_preload_get');
Done!
Change Admin Columns:
add_action( "manage_favor_posts_columns", "change_columns" );
function change_columns( $cols ) {
$cols = array(
'cb' => '<input type="checkbox" />',
'title' => __( 'Título del favor', 'trans' ),
'usuarios_registrados' => __('Usuarios Registrados', 'trans'),
'date' => __( 'Fecha publicación', 'trans' ),
);
return $cols;
}
add_action( "manage_posts_custom_column", "custom_columns_phi", 10, 2 );
Add output metas and delete link in columns:
function custom_columns_phi( $column, $post_id ) {
switch ( $column ) {
case "usuarios_registrados":
$favor_post_meta_datos = get_post_meta ($post_id, 'usuarios_favores');
foreach($favor_post_meta_datos as $term_post){
$user_phi_name = get_userdata ($term_post);
?>
<li><?echo $user_phi_name->first_name;?> | Cancelar</li>
<?
}
break;
}
}
Add init function in admin screen:
function phi_admin_preload_get () {
if ( isset($_GET['value_phi_user'] )) {
$phi_get_post = $_GET['value_phi_post'];
$phi_get_user = $_GET['value_phi_user'];
delete_post_meta ($phi_get_post, 'usuarios_favores', $phi_get_user);
delete_user_meta ($phi_get_user, 'favores', $phi_get_post );
}
}
add_action ('admin_init', 'phi_admin_preload_get');

Resources