Show multiple product custom fields values in cart on Woocommerce - php

I have a problem with custom fields & values from my product page appearing on the cart page. As you can see from the screenshots, I have three fields: "Color," "Texto1" and "Texto2" and only the first seems to appear on my cart page.
This is the code that print the fields on the product page:
// Field 1
if( ! empty( $FieldType1 ) ){
if( $FieldType1 == "TEXT AREA"){
echo '<div>
<label>'.$FieldName1.':<br></label> <textarea name="FieldTypeValue1" maxlength="'.$FieldLenght1.'" rows="2" cols="80" placeholder="" required></textarea>
</div><br>';
}
if( $FieldType1 == "TEXT BOX"){
echo '<div>
<label>'.$FieldName1.':<br></label> <input type="text" maxlength="'.$FieldLenght1.'" name="FieldTypeValue1" value="" required>
</div><br>';
}
if( $FieldType1 == "DROP DOWN"){
echo '<div>
<label>'.$FieldName1.':<br></label>
<select name="FieldTypeValue1">';
foreach ($Dropdown1Content as $Dropdown1IndividualContent) {
echo '<option>';
echo $Dropdown1IndividualContent;
echo '</option>';
}
echo '</select></div><br>';
}
}
// Field 2
if( ! empty( $FieldType2 ) ){
if( $FieldType2 == "TEXT AREA"){
echo '<div>
<label>'.$FieldName2.':<br></label> <textarea name="FieldTypeValue2" maxlength="'.$FieldLenght2.'" rows="2" cols="80" placeholder="" required></textarea>
</div><br>';
}
if( $FieldType2 == "TEXT BOX"){
echo '<div>
<label>'.$FieldName2.':<br></label> <input type="text" maxlength="'.$FieldLenght2.'" name="FieldTypeValue2" value="" required>
</div><br>';
}
if( $FieldType2 == "DROP DOWN"){
echo '<div>
<label>'.$FieldName2.':<br></label>
<select name="FieldTypeValue2">';
foreach ($Dropdown2Content as $Dropdown2IndividualContent) {
echo '<option>';
echo $Dropdown2IndividualContent;
echo '</option>';
}
echo '</select></div><br>';
}
}
// Field 3
if( ! empty( $FieldType3 ) ){
if( $FieldType3 == "TEXT AREA"){
echo '<div>
<label>'.$FieldName3.':<br></label> <textarea name="FieldTypeValue3" maxlength="'.$FieldLenght3.'" rows="2" cols="80" placeholder="" required></textarea>
</div><br>';
}
if( $FieldType3 == "TEXT BOX"){
echo '<div>
<label>'.$FieldName3.':<br></label> <input type="text" maxlength="'.$FieldLenght3.'" name="FieldTypeValue3" value="" required>
</div><br>';
}
if( $FieldType3 == "DROP DOWN"){
echo '<div>
<label>'.$FieldName3.':<br></label>
<select name="FieldTypeValue3">';
foreach ($Dropdown3Content as $Dropdown3IndividualContent) {
echo '<option>';
echo $Dropdown3IndividualContent;
echo '</option>';
}
echo '</select></div><br>';
}
}
This is the code that saves the value of the fields on the product page
// Store custom field label and value in cart item data
add_action( 'woocommerce_add_cart_item_data','save_my_custom_checkout_field', 10, 2 );
function save_my_custom_checkout_field( $cart_item_data, $product_id ) {
if( isset( $_REQUEST['FieldTypeValue1'] ) ) {
$cart_item_data['custom_data']['label'] = get_post_meta($product_id, 'FieldName1', true);
$cart_item_data['custom_data']['value'] = sanitize_text_field( $_REQUEST['FieldTypeValue1'] );
$cart_item_data['custom_data']['ukey'] = md5( microtime().rand() );
}
return $cart_item_data;
if( isset( $_REQUEST['FieldTypeValue2'] ) ) {
$cart_item_data['custom_data']['label'] = get_post_meta($product_id, 'FieldName2', true);
$cart_item_data['custom_data']['value'] = sanitize_text_field( $_REQUEST['FieldTypeValue2'] );
$cart_item_data['custom_data']['ukey'] = md5( microtime().rand() );
}
return $cart_item_data;
if( isset( $_REQUEST['FieldTypeValue3'] ) ) {
$cart_item_data['custom_data']['label'] = get_post_meta($product_id,'FieldName3', true);
$cart_item_data['custom_data']['value'] = sanitize_text_field( $_REQUEST['FieldTypeValue3'] );
$cart_item_data['custom_data']['ukey'] = md5( microtime().rand() );
}
return $cart_item_data;
And this is the one that print the values on the cart:
// Display items custom fields label and value in cart and checkout pages
add_filter( 'woocommerce_get_item_data', 'render_meta_on_cart_and_checkout', 10, 2 );
function render_meta_on_cart_and_checkout( $cart_data, $cart_item ){
$custom_items = array();
/* Woo 2.4.2 updates */
if( !empty( $cart_data ) ) {
$custom_items = $cart_data;
}
if( isset( $cart_item['custom_data'] ) ) {
$custom_items[] = array(
'name' => $cart_item['custom_data']['label'],
'value' => $cart_item['custom_data']['value'],
);
}
return $custom_items;
}
The Custom fields on product page:
The product in cart (with the missing data):
I'm not sure if the problem is at the point where values are saved or at the point where they are printed.
Any help would be much appreciated.

Try this hooked functions instead, where I have revisited your code to make it work:
// Store custom field label and value in cart item data
add_filter( 'woocommerce_add_cart_item_data','save_my_custom_checkout_field', 20, 2 );
function save_my_custom_checkout_field( $cart_item_data, $product_id ) {
$label1 = get_post_meta( $product_id, 'FieldName1', true );
$label2 = get_post_meta( $product_id, 'FieldName2', true );
$label3 = get_post_meta( $product_id, 'FieldName3', true );
if( isset( $_REQUEST['FieldTypeValue1'] ) && ! empty( $label1 ) )
$cart_item_data['custom_data']['1'] = array(
'label' => $label1,
'value' => sanitize_text_field( $_REQUEST['FieldTypeValue1'] ),
);
if( isset( $_REQUEST['FieldTypeValue2'] ) && ! empty( $label2 ) )
$cart_item_data['custom_data']['2'] = array(
'label' => $label2,
'value' => sanitize_text_field( $_REQUEST['FieldTypeValue2'] ),
);
if( isset( $_REQUEST['FieldTypeValue3'] ) && ! empty( $label3 ) )
$cart_item_data['custom_data']['3'] = array(
'label' => $label3,
'value' => sanitize_text_field( $_REQUEST['FieldTypeValue3'] ),
);
if( count($cart_item_data['custom_data']) > 0 )
$cart_item_data['custom_data']['key'] = md5( microtime().rand() );
return $cart_item_data;
}
// Display items custom fields label and value in cart and checkout pages
add_filter( 'woocommerce_get_item_data', 'render_meta_on_cart_and_checkout', 20, 2 );
function render_meta_on_cart_and_checkout( $cart_data, $cart_item ){
$custom_items = array();
if( !empty( $cart_data ) )
$custom_items = $cart_data;
if( isset( $cart_item['custom_data'] ) ) {
foreach( $cart_item['custom_data'] as $key => $custom_data ){
if( $key != 'key' ){
$custom_items[] = array(
'name' => $custom_data['label'],
'value' => $custom_data['value'],
);
}
}
}
return $custom_items;
}
Code goes in function.php file of your active child theme (or active theme).
Tested and works… You will get something like that:
For testing I have used the following to display the 3 custom fields on single product page:
// Displaying 3 custom fields on single product pages
add_action( 'woocommerce_before_add_to_cart_button', 'add_custom_fields_single_product', 20 );
function add_custom_fields_single_product(){
global $product;
echo '<div>
<label>'.__('Color').': </label><br>
<input type="text" name="FieldTypeValue1" value="" required>
</div><br>';
echo '<div>
<label>'.__('Texto 1').': </label><br>
<input type="text" name="FieldTypeValue2" value="" required>
</div><br>';
echo '<div>
<label>'.__('Texto 2').': </label><br>
<input type="text" name="FieldTypeValue3" value="" required>
</div><br>';
}
Changing the following for testing purpose only (in the functions code):
$label1 = get_post_meta( $product_id, 'FieldName1', true );
$label2 = get_post_meta( $product_id, 'FieldName2', true );
$label3 = get_post_meta( $product_id, 'FieldName3', true );
by:
$label1 = __('Color');
$label2 = __('Texto 1');
$label3 = __('Texto 2');

Related

Metabox with multiple custom fields for WooCommerce admin order pages

I found the below code the other day, and now my client wants two more fields. If I add it again to my snippet plugin it says “Cannot redeclare function set_custom_edit_shop_order_columns.”. Could someone kindly help me to change the code with two more custom fields?
I have changed custom_column to courier_reference and want another text field tracking_number and one more is shipping_date with a date picker rather than a text box.
Any help is appreciated.
//from::https://codex.wordpress.org/Plugin_API/Action_Reference/manage_posts_custom_column
// For displaying in columns.
add_filter( 'manage_edit-shop_order_columns', 'set_custom_edit_shop_order_columns' );
function set_custom_edit_shop_order_columns($columns) {
$columns['custom_column'] = __( 'Custom Column', 'your_text_domain' );
return $columns;
}
// Add the data to the custom columns for the order post type:
add_action( 'manage_shop_order_posts_custom_column' , 'custom_shop_order_column', 10, 2 );
function custom_shop_order_column( $column, $post_id ) {
switch ( $column ) {
case 'custom_column' :
echo esc_html( get_post_meta( $post_id, 'custom_column', true ) );
break;
}
}
// For display and saving in order details page.
add_action( 'add_meta_boxes', 'add_shop_order_meta_box' );
function add_shop_order_meta_box() {
add_meta_box(
'custom_column',
__( 'Custom Column', 'your_text_domain' ),
'shop_order_display_callback',
'shop_order'
);
}
// For displaying.
function shop_order_display_callback( $post ) {
$value = get_post_meta( $post->ID, 'custom_column', true );
echo '<textarea style="width:100%" id="custom_column" name="custom_column">' . esc_attr( $value ) . '</textarea>';
}
// For saving.
function save_shop_order_meta_box_data( $post_id ) {
// If this is an autosave, our form has not been submitted, so we don't want to do anything.
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
// Check the user's permissions.
if ( isset( $_POST['post_type'] ) && 'shop_order' == $_POST['post_type'] ) {
if ( ! current_user_can( 'edit_shop_order', $post_id ) ) {
return;
}
}
// Make sure that it is set.
if ( ! isset( $_POST['custom_column'] ) ) {
return;
}
// Sanitize user input.
$my_data = sanitize_text_field( $_POST['custom_column'] );
// Update the meta field in the database.
update_post_meta( $post_id, 'custom_column', $my_data );
}
add_action( 'save_post', 'save_shop_order_meta_box_data' );
Updated... You just need to have multiple different slugs in the same functions. For your desired 3 custom fields use the following:
// Add columns to admin orders table.
add_filter( 'manage_edit-shop_order_columns', 'set_custom_edit_shop_order_columns' );
function set_custom_edit_shop_order_columns($columns) {
$columns['courier_reference'] = __( 'Courier reference', 'woocommerce' );
$columns['tracking_number'] = __( 'Tracking number', 'woocommerce' );
$columns['shipping_date'] = __( 'Shipping date', 'woocommerce' );
return $columns;
}
// Add the data to the custom columns for the order post type:
add_action( 'manage_shop_order_posts_custom_column' , 'custom_shop_order_column', 10, 2 );
function custom_shop_order_column( $column, $post_id ) {
switch ( $column ) {
case 'courier_reference' :
echo esc_html( get_post_meta( $post_id, 'courier_reference', true ) );
break;
case 'tracking_number' :
echo esc_html( get_post_meta( $post_id, 'tracking_number', true ) );
break;
case 'shipping_date' :
echo esc_html( get_post_meta( $post_id, 'shipping_date', true ) );
break;
}
}
// Add a metabox.
add_action( 'add_meta_boxes', 'add_shop_order_meta_box' );
function add_shop_order_meta_box() {
add_meta_box(
'custom_meta_box',
__( 'Tracking information', 'woocommerce' ),
'shop_order_content_callback',
'shop_order'
);
}
// For displaying metabox content
function shop_order_content_callback( $post ) {
// Textarea Field
$courier_reference = get_post_meta( $post->ID, 'courier_reference', true );
echo '<p>' . __( 'Courier reference', 'woocommerce' ) . '<br>
<textarea style="width:100%" id="courier_reference" name="courier_reference">' . esc_attr( $courier_reference ) . '</textarea></p>';
// Text field
$tracking_number = get_post_meta( $post->ID, 'tracking_number', true );
echo '<p>' . __( 'Tracking number', 'woocommerce' ) . '<br>
<input type="text" style="width:100%" id="tracking_number" name="tracking_number" value="' . esc_attr( $tracking_number ) . '"></p>';
// Date picker field
$shipping_date = get_post_meta( $post->ID, 'shipping_date', true );
echo '<p>' . __( 'shipping_date', 'woocommerce' ) . '<br>
<input type="date" style="width:100%" id="shipping_date" name="shipping_date" value="' . esc_attr( $shipping_date ) . '"></p>';
}
// For saving the metabox data.
add_action( 'save_post_shop_order', 'save_shop_order_meta_box_data' );
function save_shop_order_meta_box_data( $post_id ) {
// If this is an autosave, our form has not been submitted, so we don't want to do anything.
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
// Check the user's permissions.
if ( ! current_user_can( 'edit_shop_order', $post_id ) ) {
return;
}
// Make sure that 'shipping_date' is set.
if ( isset( $_POST['courier_reference'] ) ) {
// Update the meta field in the database.
update_post_meta( $post_id, 'courier_reference', sanitize_textarea_field( $_POST['courier_reference'] ) );
}
// Make sure that 'tracking_number' it is set.
if ( isset( $_POST['tracking_number'] ) ) {
// Update the meta field in the database.
update_post_meta( $post_id, 'tracking_number', sanitize_text_field( $_POST['tracking_number'] ) );
}
// Make sure that 'shipping_date' is set.
if ( isset( $_POST['shipping_date'] ) ) {
// Update the meta field in the database.
update_post_meta( $post_id, 'shipping_date', sanitize_text_field( $_POST['shipping_date'] ) );
}
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.

Empty order item metadata for variable product at first in Woocommerce

The following code adds editable short description of the product as order item metadata in Woocommerce. The code is working as expected for simple products but for variable products the $item->get_formatted_meta_data('') returns empty array at first and only after editing the item, the short description shows as expected.
<?php
/**
* Add product description meta to order item
*/
add_action( 'woocommerce_before_order_itemmeta', 'add_order_item_description_meta', 10, 3 );
function add_order_item_description_meta( $item_id, $item, $product ) {
// Add only if not present
$product_description_meta = wc_get_order_item_meta( $item_id, '_product_short_desc', true );
if( empty( $product_description_meta ) ) {
if( $product->is_type('variation') ) {
$parent_product = wc_get_product( $product->get_parent_id() );
$excerpt = $product->get_description();
$excerpt = empty($excerpt) ? $parent_product->get_short_description() : $excerpt;
} else {
$excerpt = $product->get_short_description();
}
wc_add_order_item_meta( $item_id, '_product_short_desc', $excerpt );
}
}
/**
* Hide product description meta
*/
add_filter( 'woocommerce_hidden_order_itemmeta', 'custom_hidden_order_itemmeta' );
function custom_hidden_order_itemmeta( $hidden_order_itemmeta ) {
$hidden_order_itemmeta[] = '_product_short_desc';
return $hidden_order_itemmeta;
}
/**
* Add custom column to display product description meta
*/
add_action( 'woocommerce_admin_order_item_headers', 'custom_admin_order_items_headers', 20, 1 );
function custom_admin_order_items_headers( $order ) {
echo '<th class="item_short_description">';
echo __('Short Description', 'woocommerce') . '</th>';
}
/**
* Custom column content in table
*/
add_action( 'woocommerce_admin_order_item_values', 'custom_admin_order_item_values', 20, 3 );
function custom_admin_order_item_values( $product, $item, $item_id ) {
?>
<td class="product_short_desc">
<?php
if( $meta_data = $item->get_formatted_meta_data( '' ) ) {
$meta = array_filter( $meta_data, function( $value, $key ) {
return '_product_short_desc' === $value->key;
}, ARRAY_FILTER_USE_BOTH );
if( ! empty( $meta ) ) {
// Get the key of first value
$meta_id = 0;
foreach( $meta as $key => $value) {
$meta_id = $key;
break;
}
$product_desc_meta = $meta[$meta_id];
?>
<div class="view">
<?php echo wp_kses_post( force_balance_tags( $product_desc_meta->display_value ) ); ?>
</div>
<div class="edit" style="display: none;">
<input type="hidden" placeholder="<?php esc_attr_e( 'Name (required)', 'woocommerce' ); ?>" name="meta_key[<?php echo esc_attr( $item_id ); ?>][<?php echo esc_attr( $meta_id ); ?>]" value="<?php echo esc_attr( $product_desc_meta->key ); ?>" />
<textarea placeholder="<?php esc_attr_e( 'Short Description', 'woocommerce' ); ?>" name="meta_value[<?php echo esc_attr( $item_id ); ?>][<?php echo esc_attr( $meta_id ); ?>]"><?php echo esc_textarea( rawurldecode( $product_desc_meta->value ) ); ?></textarea>
</div>
<?php
}
} else {
echo '-';
} ?>
</td>
<?php
}
For simple product the Short Description column is displaying value when adding the item to order but for variable product it shows - as it goes into else condition of function custom_admin_order_item_values at first and then after editing the item, it displays the short description correctly.
Here's screenshot for the simple and variable product added without being edited:
Please help to find the underlying bug.
UPDATE: Anyone trying to help on this, I can confirm that problem lies either in first hooked function i.e. add_order_item_description_meta or in the Woocommerce core because even if you comment out the later hooks and their respective functions the same problem is there.
So the meta data for the variable product is not loaded first time when product is added to the order, but when it is refreshed such as by editing it, the meta data loads fine. Also note as I mentioned earlier the meta data loads as expected for simple products at first time without need of refresh of order items.
I have tried your code and it works using
$meta = array_filter( $meta_data, function( $value ) {
return '_product_short_desc' === $value->key;
} );
instead of
$meta = array_filter( $meta_data, function( $value, $key ) {
return '_product_short_desc' === $value->key;
}, ARRAY_FILTER_USE_BOTH );
and adding if statement in add_order_item_description_meta
function add_order_item_description_meta( $item_id, $item, $product ) {
if ( !$product ) return;
/* … rest of the code … */
Here's a screenshot:

How To Show Chechbox Result From Metabox To Single Post Wordpress?

Ask to everyone, i have problem. Here i try to use multiple chechbox to my custom post metabox.
<?php
function prodetail() {
add_meta_box('pro_metabox', 'Detail Property', 'pro_metabox', 'property', 'normal', 'default');
}
function pro_metabox() {
global $post;
echo '<input type="hidden" name="eventmeta_noncename" id="eventmeta_noncename" value="' .
wp_create_nonce( plugin_basename(__FILE__) ) . '" />';
$postmeta = maybe_unserialize( get_post_meta( $post->ID, 'elements', true ) );
$elements = array(
'pool' => 'Pool',
'garage' => 'Garage',
'balcon' => 'Balcon',
'yard' => 'Yard',
'internet' => 'Internet'
);
foreach ( $elements as $id => $element) {
if ( is_array( $postmeta ) && in_array( $id, $postmeta ) ) {
$checked = 'checked="checked"';
} else {
$checked = null;
}
?>
<div class="pro-inn">
<div class="procols">
<div class="pro-inn">
<input type="checkbox" name="multval[]" value="<?php echo $id; ?>" <?php echo $checked; ?> />
<?php echo $element;?>
</div>
</div>
</div>
<?php
}
}
function pro_meta($post_id, $post) {
if ( !wp_verify_nonce( $_POST['eventmeta_noncename'], plugin_basename(__FILE__) )) {
return $post->ID;
}
if ( !current_user_can( 'edit_post', $post->ID ))
return $post->ID;
if ( ! empty( $_POST['multval'] ) ) {
update_post_meta( $post_id, 'elements', $_POST['multval'] );
} else {
delete_post_meta( $post_id, 'elements' );
}
}
add_action('save_post', 'pro_meta', 1, 2);
?>
help me to add code to show this checked result to single.php because my code use foreach just show Array text not show text like Pool Garage Balcon ect.
Thanks
Use this code in your single.php file for your custom post
$meta_value = get_post_meta( $post->ID, 'elements', true );
foreach($meta_value as $key=>$value){
echo $value . ' ';
}
It will show results same as you mentioned in the question ie:
(Pool Garage Balcon ect.)

WordPress - how to add custom meta box to a specific admin page?

How can I add my custom meta box to a specific page only on the admin page?
Here is my custom meta box code which I got it from here:
/**
* Adds a meta box to the post editing screen
*/
function prfx_custom_meta() {
add_meta_box( 'prfx_meta', __( 'Meta Box Title', 'prfx-textdomain' ), 'prfx_meta_callback', array( 'post', 'page') );
}
add_action( 'add_meta_boxes', 'prfx_custom_meta' );
/**
* Outputs the content of the meta box
*/
function prfx_meta_callback( $post ) {
// echo 'This is a meta box';
wp_nonce_field( basename( __FILE__ ), 'prfx_nonce' );
$prfx_stored_meta = get_post_meta( $post->ID );
if ($post_slug == 'home') {
?>
<p>
<label for="meta-text" class="prfx-row-title"><?php _e( 'Example Text Input', 'prfx-textdomain' )?></label>
<input type="text" name="meta-text" id="meta-text" value="<?php if ( isset ( $prfx_stored_meta['meta-text'] ) ) echo $prfx_stored_meta['meta-text'][0]; ?>" />
</p>
<?php
}
}
/**
* Saves the custom meta input
*/
function prfx_meta_save( $post_id ) {
// Checks save status
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
$is_valid_nonce = ( isset( $_POST[ 'prfx_nonce' ] ) && wp_verify_nonce( $_POST[ 'prfx_nonce' ], basename( __FILE__ ) ) ) ? 'true' : 'false';
// Exits script depending on save status
if ( $is_autosave || $is_revision || !$is_valid_nonce ) {
return;
}
// Checks for input and sanitizes/saves if needed
if( isset( $_POST[ 'meta-text' ] ) ) {
update_post_meta( $post_id, 'meta-text', sanitize_text_field( $_POST[ 'meta-text' ] ) );
}
}
add_action( 'save_post', 'prfx_meta_save' );
I just want to add the meta box to my home page. but now on other pages and posts I still see the meta title:
Any idea how I stop it from showing on other pages and posts?
EDIT:
/**
* Add custom meta box to a specific page in the WP admin.
*
* # http://themefoundation.com/wordpress-meta-boxes-guide/
* # http://www.farinspace.com/page-specific-wordpress-meta-box/
*/
function my_meta_init() {
// Get post/page ID.
$post_id = $_GET['post'] ? $_GET['post'] : $_POST['post_ID'] ;
// Get post/page slug.
$post = get_post($post_id);
$slug = $post->post_name;
// checks for post/page slug.
if ($slug == 'home') {
add_meta_box( 'prfx_meta', __( 'Meta Box Title', 'prfx-textdomain' ), 'prfx_meta_callback', array( 'post', 'page') );
}
add_action( 'add_meta_boxes', 'prfx_meta_save' );
}
add_action('admin_init','my_meta_init');
/**
* Outputs the content of the meta box
*/
function prfx_meta_callback( $post ) {
// echo 'This is a meta box';
wp_nonce_field( basename( __FILE__ ), 'prfx_nonce' );
$prfx_stored_meta = get_post_meta( $post->ID );
?>
<p>
<label for="meta-text" class="prfx-row-title"><?php _e( 'Example Text Input', 'prfx-textdomain' )?></label>
<input type="text" name="meta-text" id="meta-text" value="<?php if ( isset ( $prfx_stored_meta['meta-text'] ) ) echo $prfx_stored_meta['meta-text'][0]; ?>" />
</p>
<?php
}
/**
* Saves the custom meta input
*/
function prfx_meta_save( $post_id ) {
// Checks save status
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
$is_valid_nonce = ( isset( $_POST[ 'prfx_nonce' ] ) && wp_verify_nonce( $_POST[ 'prfx_nonce' ], basename( __FILE__ ) ) ) ? 'true' : 'false';
// Exits script depending on save status
if ( $is_autosave || $is_revision || !$is_valid_nonce ) {
return;
}
// Checks for input and sanitizes/saves if needed
if( isset( $_POST[ 'meta-text' ] ) ) {
update_post_meta( $post_id, 'meta-text', sanitize_text_field( $_POST[ 'meta-text' ] ) );
}
}
add_action( 'save_post', 'prfx_meta_save' );
You can try this condition
add_action('admin_init','my_meta_init');
function my_meta_init()
{
$post_id = $_GET['post'] ? $_GET['post'] : $_POST['post_ID'] ;
// checks for post/page ID
if ($post_id == '84')
{
add_meta_box('my_all_meta_1', 'My Custom Meta Box 1', 'my_meta_setup_1', 'page', 'normal', 'high');
}
add_action('save_post','my_meta_save');
}
/**
* Adds a meta box to the post editing screen
*/
function prfx_custom_meta() {
$current_user = wp_get_current_user();
if($current_user->roles[0] === 'administrator') {
add_meta_box( 'prfx_meta', __( 'Meta Box Title', 'prfx-textdomain' ), 'prfx_meta_callback', array( 'post', 'page') );
}
}
add_action( 'add_meta_boxes', 'prfx_custom_meta' );
/**
* Outputs the content of the meta box
*/
function prfx_meta_callback( $post ) {
// echo 'This is a meta box';
wp_nonce_field( basename( __FILE__ ), 'prfx_nonce' );
$prfx_stored_meta = get_post_meta( $post->ID );
if ($post_slug == 'home') {
?>
<p>
<label for="meta-text" class="prfx-row-title"><?php _e( 'Example Text Input', 'prfx-textdomain' )?></label>
<input type="text" name="meta-text" id="meta-text" value="<?php if ( isset ( $prfx_stored_meta['meta-text'] ) ) echo $prfx_stored_meta['meta-text'][0]; ?>" />
</p>
<?php
}
}
/**
* Saves the custom meta input
*/
function prfx_meta_save( $post_id ) {
// Checks save status
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
$is_valid_nonce = ( isset( $_POST[ 'prfx_nonce' ] ) && wp_verify_nonce( $_POST[ 'prfx_nonce' ], basename( __FILE__ ) ) ) ? 'true' : 'false';
// Exits script depending on save status
if ( $is_autosave || $is_revision || !$is_valid_nonce ) {
return;
}
// Checks for input and sanitizes/saves if needed
if( isset( $_POST[ 'meta-text' ] ) ) {
update_post_meta( $post_id, 'meta-text', sanitize_text_field( $_POST[ 'meta-text' ] ) );
}
}
add_action( 'save_post', 'prfx_meta_save' );
Use this js it will resolve your problem. this will show the metabox on perticular template or page..
(function($){
$(document).ready(function() {
var $page_template = $('#pageid')
,$metabox1 = $('#metaboxid');
$page_template.change(function() {
if ($(this).val() == 'templatename') {
$metabox1.show();
} else {
$metabox1.hide();
}
}).change();
});
})(jQuery);
if you are using this in admin then use admin hook and add this code in functions.php

How do I add a field on the WooCommerce product page?

I am trying to add a text field that accepts a text value from user on the product page before he/she clicks the "Add To Card" button. Here is the code that I have added in functions.php file:
function action_woocommerce_before_add_to_cart_button( )
{
// make action magic happen here...
echo "<input type='text' name='engrave-text' id='engrave-text' placeholder='Your Engraving Text'>";
};
// add the action
add_action( 'woocommerce_before_add_to_cart_button', 'action_woocommerce_before_add_to_cart_button', 10, 0 );
//Store the custom field
add_filter( 'woocommerce_add_cart_item_data', 'add_cart_item_custom_data_vase', 10, 2 );
function add_cart_item_custom_data_vase( $cart_item_meta, $product_id ) {
global $woocommerce;
$cart_item_meta['test_field'] = $_POST['engrave-text'];
return $cart_item_meta;
}
//Get it from the session and add it to the cart variable
function get_cart_items_from_session( $item, $values, $key ) {
if ( array_key_exists( 'test_field', $values ) )
$item[ 'Engraved-Text' ] = $values['test_field'];
return $item;
}
add_filter( 'woocommerce_get_cart_item_from_session', 'get_cart_items_from_session', 1, 3 );
But it is not working. Can you please help?
Thank you
I figured it out. The following code works:
function action_woocommerce_before_add_to_cart_button( )
{
// make action magic happen here...
echo "<input type='text' name='engrave-text' id='engrave-text' placeholder='Your Engraving Text'>";
};
// add the action
add_action( 'woocommerce_before_add_to_cart_button', 'action_woocommerce_before_add_to_cart_button', 10, 0 );
function engrave_text_validation() {
if ( empty( $_REQUEST['engrave-text'] ) ) {
wc_add_notice( __( 'Please enter a Name for Engraving', 'woocommerce' ), 'error' );
return false;
}
return true;
}
add_action( 'woocommerce_add_to_cart_validation', 'engrave_text_validation', 10, 3 );
function save_engrave_text_field( $cart_item_key, $product_id = null, $quantity= null, $variation_id= null, $variation= null ) {
if( isset( $_REQUEST['engrave-text'] ) ) {
WC()->session->set( $cart_item_key.'_engrave_text', $_REQUEST['engrave-text'] );
}
}
add_action( 'woocommerce_add_to_cart', 'save_engrave_text_field', 1, 5 );
function render_meta_on_cart_item( $title = null, $cart_item = null, $cart_item_key = null ) {
if( $cart_item_key && WC()->session->__isset( $cart_item_key.'_engrave_text' ) ) {
echo $title. '<dl class="">
<dt class="">Engrave Text : </dt>
<dd class=""><p>'. WC()->session->get( $cart_item_key.'_engrave_text') .'</p></dd>
</dl>';
}else {
echo $title;
}
}
add_filter( 'woocommerce_cart_item_name', 'render_meta_on_cart_item', 1, 3 );
function render_meta_on_checkout_order_review_item( $quantity = null, $cart_item = null, $cart_item_key = null ) {
if( $cart_item_key && WC()->session->__isset( $cart_item_key.'_engrave_text' ) ) {
echo $quantity. '<dl class="">
<dt class="">Engrave Text: </dt>
<dd class=""><p>'. WC()->session->get( $cart_item_key.'_engrave_text') .'</p></dd>
</dl>';
}
}
add_filter( 'woocommerce_checkout_cart_item_quantity', 'render_meta_on_checkout_order_review_item', 1, 3 );
function engrave_text_order_meta_handler( $item_id, $values, $cart_item_key ) {
if( WC()->session->__isset( $cart_item_key.'_engrave_text' ) ) {
wc_add_order_item_meta( $item_id, "Engrave Text", WC()->session->get( $cart_item_key.'_engrave_text') );
}
}
add_action( 'woocommerce_add_order_item_meta', 'engrave_text_order_meta_handler', 1, 3 );
function engrave_force_individual_cart_items($cart_item_data, $product_id)
{
$unique_cart_item_key = md5( microtime().rand() );
$cart_item_data['unique_key'] = $unique_cart_item_key;
return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data','engrave_force_individual_cart_items', 10, 2 );
You can add the fields or any thing like image or text to display using this hook
add_action( 'woocommerce_before_add_to_cart_button', 'addFieldsBeforeAddToCart' );
/* This function will add text field in the front end when plugin is activated*/
function addFieldsBeforeAddToCart() {
?>
<table>
<tr>
<td>
<?php _e( "Name:", "aoim"); ?>
</td>
<td>
<input type = "text" name = "customerName" id = "customerName" placeholder = "Name on Gift Card">
</td>
</tr>
<tr>
<td>
<?php _e( "Message:", "aoim"); ?>
</td>
<td>
<input type = "text" name = "customerMessage" id = "customerMessage" placeholder = "Your Message on Gift Card">
</td>
</tr>
</table>
<?php
}
use this hook in functions.php or in your plugin file

Categories