I'm working on a WordPress/Dokan plugin. I am looking for a way to add a new field by two selectable options, New and Used product. Also, The visitors can filter the products in the shop page or search results page by New and Used products. I would really appreciate it if someone can help me?
I tried the following code. But when I add it to the child-theme, it disrupts the website function.
// ****adding extra field in single product page START****
// Adding extra field on New product popup/without popup form
add_action( 'dokan_new_product_after_product_tags','new_product_field',10 );
function new_product_field(){ ?>
<div class="dokan-form-group">
<label class="dokan-control-label" for=""><?php _e( 'Item condition', 'dokan' ); ?></label>
<div class="dokan-form-group">
<select name="new_field" class="dokan-form-control">
<option value=""><?php _e( '', 'dokan' ) ?></option>
<option value="new"><?php _e( 'New', 'dokan' ) ?></option>
<option value="used"><?php _e( 'Used', 'dokan' ) ?></option>
</select>
</div>
</div>
<?php
}
/*
* Saving product field data for edit and update
*/
add_action( 'dokan_new_product_added','save_add_product_meta', 10, 2 );
add_action( 'dokan_product_updated', 'save_add_product_meta', 10, 2 );
function save_add_product_meta($product_id, $postdata){
if ( ! dokan_is_user_seller( get_current_user_id() ) ) {
return;
}
// if ( ! empty( $postdata['new_field'] ) ) {
// update_post_meta( $product_id, 'new_field', $postdata['new_field'] );
// }
update_post_meta( $product_id, 'new_field', $postdata['new_field'] );
}
/*
* Showing field data on product edit page
*/
add_action('dokan_product_edit_after_product_tags','show_on_edit_page',99,2);
function show_on_edit_page($post, $post_id){
$new_field = get_post_meta( $post_id, 'new_field', true );
?>
<div class="dokan-form-group">
<label class="dokan-control-label" for=""><?php _e( 'Item condition', 'dokan' ); ?></label>
<select name="new_field" class="dokan-form-control">
<option value="new" <?php echo ( "new_field" == 'new' ) ? 'selected' : 'Used' ?>><?php _e( 'New', 'dokan' ) ?></option>
<option value="used" <?php echo ( "new_field" == 'used' ) ? 'selected' : 'New' ?>><?php _e( 'Used', 'dokan' ) ?></option>
</select>
</div> <?php
}
// showing on single product page
add_action('woocommerce_single_product_summary','show_product_code',13);
function show_product_code(){
global $product;
if ( empty( $product ) ) {
return;
}
$new_field = get_post_meta( $product->get_id(), 'new_field', true );
if (empty($new_field)) exit;
if ( ! empty( $new_field ) ) {
?>
<span><?php echo esc_attr__( 'Item condition:', 'dokan' ); ?> <strong><?php echo esc_attr( $new_field ); ?></strong></span>
<?php
}
}
// ****adding extra field in single product page END****
Here is updated code you should try