Skip to content

Instantly share code, notes, and snippets.

@nvourva
Last active April 16, 2019 10:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nvourva/c2d84c819c033feabf4820e20544938c to your computer and use it in GitHub Desktop.
Save nvourva/c2d84c819c033feabf4820e20544938c to your computer and use it in GitHub Desktop.
Create a custom WooCommerce product field. It is added in the inventory tab and displayed below the single product title.
<?php
/**
* Plugin Name: Custom Product Fields for WooCommerce
* Description: This small plugin will generate and display a custom product field.
* Version: 1.0.0
* Author: nvourva
*/
add_action( 'woocommerce_product_options_stock_fields', 'my_restock_notice_field' );
function my_restock_notice_field() {
global $woocommerce, $post;
woocommerce_wp_textarea_input(
array(
'id' => 'my_restock_notice',
'placeholder' => 'Back in stock next week!',
'label' => 'Restock notice',
'description' => 'Let your customers know when the product will be back in stock.',
'desc_tip' => 'true',
)
);
}
add_action( 'woocommerce_process_product_meta', 'my_restock_notice_save_data' );
function my_restock_notice_save_data( $post_id ) {
if ( 'no' === get_option( 'woocommerce_manage_stock' ) ) {
return;
}
$my_restock_notice_textarea = $_POST['my_restock_notice'];
if ( ! empty( $my_restock_notice_textarea ) ) {
update_post_meta( $post_id, 'my_restock_notice', esc_html( $my_restock_notice_textarea ) );
}
}
add_filter( 'woocommerce_single_product_summary', 'my_restock_notice_display', 6 );
function my_restock_notice_display() {
global $product;
$notice = get_post_meta( $product->get_ID(), 'my_restock_notice', true );
$stock_status = $product->get_stock_status();
if ( empty( $notice ) || 0 < $product->get_stock_quantity() || 'outofstock' !== $stock_status ) {
return;
} else {
echo '<p class="my-restock-notice">' . esc_html( $notice ) . '</p>';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment