Delete metadata in WP admin custom columns - wordpress

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');

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 field as item meta data on the Order

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;
}

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
}

Adding New Stock Status to Products in Woocommerce [duplicate]

I am using the following code to add new stock statuses in WooCommerce 4+
The new statuses are:
Preorder
Contact us
function add_custom_stock_type() {
?>
<script type="text/javascript">
jQuery(function(){
jQuery('._stock_status_field').not('.custom-stock-status').remove();
});
</script>
<?php
woocommerce_wp_select( array( 'id' => '_stock_status', 'wrapper_class' => 'custom-stock-status', 'label' => __( 'Stock status', 'woocommerce' ), 'options' => array(
'instock' => __( 'Available', 'woocommerce' ), //changed the name
'outofstock' => __( 'Sold out', 'woocommerce' ), //changed the name
'onbackorder' => __( 'Preorder : Pending Distributor release', 'woocommerce' ), //changed the name
'contact' => __( 'Contact us for Availability', 'woocommerce' ), //added new one
'preorder' => __( 'On Preorder: Pending Distributor release', 'woocommerce' ), //added new one
), 'desc_tip' => true, 'description' => __( 'Controls whether or not the product is listed as "in stock" or "out of stock" on the frontend.', 'woocommerce' ) ) );
}
add_action('woocommerce_product_options_stock_status', 'add_custom_stock_type');
function save_custom_stock_status( $product_id ) {
update_post_meta( $product_id, '_stock_status', wc_clean( $_POST['_stock_status'] ) );
}
add_action('woocommerce_process_product_meta', 'save_custom_stock_status',99,1);
function woo_add_custom_general_fields_save_two( $post_id ){
// Select
$woocommerce_select = $_POST['_stock_status'];
if( !empty( $woocommerce_select ) )
update_post_meta( $post_id, '_stock_status', esc_attr( $woocommerce_select ) );
else
update_post_meta( $post_id, '_stock_status', '' );
}
function woocommerce_get_custom_availability( $data, $product ) {
switch( $product->stock_status ) {
case 'instock':
$data = array( 'availability' => __( 'Available', 'woocommerce' ), 'class' => 'in-stock' ); //changed name
break;
case 'outofstock':
$data = array( 'availability' => __( 'Sold Out', 'woocommerce' ), 'class' => 'out-of-stock' ); //changed name
break;
case 'onbackorder':
$data = array( 'availability' => __( 'Preorder : Pending Distributor release', 'woocommerce' ), 'class' => 'onbackorder' ); //changed name
break;
case 'contact':
$data = array( 'availability' => __( 'Contact us for Availability', 'woocommerce' ), 'class' => 'contact' ); //added new one
break;
case 'preorder':
$data = array( 'availability' => __( 'On Preorder : Pending Distributor release', 'woocommerce' ), 'class' => 'preorder' ); //added new one
break;
}
return $data;
}
add_action('woocommerce_get_availability', 'woocommerce_get_custom_availability', 10, 4);
Works:
Backend: The new status is added in the dropdown menu, I can select the status I want
Does not work:
Front end: on single product page is not showing the correct status
Backend: Display the new status on the admin products list table
Someone who can assist me with this?
Last update: 04/22 - Tested in WordPress 5.9.2 & WooCommerce 6.3.1
Code goes in functions.php file of the active child theme (or active theme).
Use woocommerce_product_stock_status_options
instead of woocommerce_product_options_stock_status.
This way you can immediately add a status instead of replace the existing dropdown
Also use woocommerce_get_availability_text & woocommerce_get_availability_class
opposite woocommerce_get_availability.
This way you don't have to add the existing statuses again
// Add new stock status options
function filter_woocommerce_product_stock_status_options( $status ) {
// Add new statuses
$status['pre_order'] = __( 'Pre order', 'woocommerce' );
$status['contact_us'] = __( 'Contact us', 'woocommerce' );
return $status;
}
add_filter( 'woocommerce_product_stock_status_options', 'filter_woocommerce_product_stock_status_options', 10, 1 );
// Availability text
function filter_woocommerce_get_availability_text( $availability, $product ) {
// Get stock status
switch( $product->get_stock_status() ) {
case 'pre_order':
$availability = __( 'Pre order', 'woocommerce' );
break;
case 'contact_us':
$availability = __( 'Contact us', 'woocommerce' );
break;
}
return $availability;
}
add_filter( 'woocommerce_get_availability_text', 'filter_woocommerce_get_availability_text', 10, 2 );
// Availability CSS class
function filter_woocommerce_get_availability_class( $class, $product ) {
// Get stock status
switch( $product->get_stock_status() ) {
case 'pre_order':
$class = 'pre-order';
break;
case 'contact_us':
$class = 'contact-us';
break;
}
return $class;
}
add_filter( 'woocommerce_get_availability_class', 'filter_woocommerce_get_availability_class', 10, 2 );
Use woocommerce_admin_stock_html to display the new stock status on the admin products list table
// Admin stock html
function filter_woocommerce_admin_stock_html( $stock_html, $product ) {
// Simple
if ( $product->is_type( 'simple' ) ) {
// Get stock status
$product_stock_status = $product->get_stock_status();
// Variable
} elseif ( $product->is_type( 'variable' ) ) {
foreach( $product->get_visible_children() as $variation_id ) {
// Get product
$variation = wc_get_product( $variation_id );
// Get stock status
$product_stock_status = $variation->get_stock_status();
/*
Currently the status of the last variant in the loop will be displayed.
So from here you need to add your own logic, depending on what you expect from your custom stock status.
By default, for the existing statuses. The status displayed on the admin products list table for variable products is determined as:
- Product should be in stock if a child is in stock.
- Product should be out of stock if all children are out of stock.
- Product should be on backorder if all children are on backorder.
- Product should be on backorder if at least one child is on backorder and the rest are out of stock.
*/
}
}
// Stock status
switch( $product_stock_status ) {
case 'pre_order':
$stock_html = '<mark class="pre-order" style="background:transparent none;color:#33ccff;font-weight:700;line-height:1;">' . __( 'Pre order', 'woocommerce' ) . '</mark>';
break;
case 'contact_us':
$stock_html = '<mark class="contact-us" style="background:transparent none;color:#cc33ff;font-weight:700;line-height:1;">' . __( 'Contact us', 'woocommerce' ) . '</mark>';
break;
}
return $stock_html;
}
add_filter( 'woocommerce_admin_stock_html', 'filter_woocommerce_admin_stock_html', 10, 2 );
Optional: if desired, the custom stock status can be used in hooks where you already have access to the $product object or you can use global $product.
1) No access to the $product object, use global $product as is the case for example with the woocommerce_shop_loop_item_title or the woocommerce_single_product_summary hook
function woocommerce_my_callback() {
// An example based on global $product
// Get the global product object
global $product;
// Is a WC product
if ( is_a( $product, 'WC_Product' ) ) {
// Get stock status
$product_stock_status = $product->get_stock_status();
// Use this line during testing, delete afterwards!
echo '<p style="color:red;font-size:20px;">DEBUG INFORMATION = ' . $product_stock_status . '</p>';
// Compare
if ( $product_stock_status == 'My custom stock status' ) {
// Etc..
}
}
}
add_action( 'woocommerce_shop_loop_item_title', 'woocommerce_my_callback', 10 );
add_action( 'woocommerce_single_product_summary', 'woocommerce_my_callback', 10 );
2) Access to the $product object, because it's passed by default to the callback function. As is the case for example with the woocommerce_get_price_html hook
function filter_woocommerce_get_price_html( $price, $product ) {
// Is a WC product
if ( is_a( $product, 'WC_Product' ) ) {
// Get stock status
$product_stock_status = $product->get_stock_status();
// Use this line during testing, delete afterwards!
echo '<p style="color:red;font-size:20px;">DEBUG INFORMATION = ' . $product_stock_status . '</p>';
// Compare
if ( $product_stock_status == 'My custom stock status' ) {
// Etc..
// $price .= ' my text';
}
}
return $price;
}
add_filter( 'woocommerce_get_price_html', 'filter_woocommerce_get_price_html', 10, 2 );
In addition to filters provided by 7uc1f3r woocommerce_product_export_product_column_stock_status filter is required to display custom stock status in exported products CSV file:
function add_custom_stock_csv_data( $_, $product ) {
$status = $product->get_stock_status( 'edit' );
switch( $status ) {
case 'pre_order':
case 'contact_us':
return $status;
case 'onbackorder':
return 'backorder';
case 'instock':
return 1;
default:
return 0;
}
}
add_filter( 'woocommerce_product_export_product_column_stock_status', 'add_custom_stock_csv_data', 10, 2 );

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>

Resources