Wordpress Meta Box Form Data Not Saving - php

My plugin is about adding FAQs to your desired page.
I have added a form within a metabox in the 'Add New Question'.
When I feed values in the form, the form data does save in
the database, but does not retain or show the values (selected)
in the form when the page updates/publishes.
Instead, the form shows the previous non-selected values (even though the
selected values do show up in the database).
<?php
function faq_manage_things($post)
{
global $post;
$post_id= $post->ID;
wp_nonce_field(basename(__FILE__),'faqs_questions_nonce');
$faq_stored_meta= get_post_meta($post->ID);
?>
<div class="wrap">
<p>
<label for="meta-select" class="prfx-row-title"><?php _e( 'Example Select Input', 'prfx-textdomain' )?></label>
<select name="meta-select" id="meta-select">
<option value="select-one" <?php if ( isset ( $prfx_stored_meta['meta-select'] ) ) selected( $prfx_stored_meta['meta-select'][0], 'select-one' ); ?>><?php _e( 'One', 'prfx-textdomain' )?></option>';
<option value="select-two" <?php if ( isset ( $prfx_stored_meta['meta-select'] ) ) selected( $prfx_stored_meta['meta-select'][0], 'select-two' ); ?>><?php _e( 'Two', 'prfx-textdomain' )?></option>';
</select>
</p>
<!-- TEXT AREA -->
<p>
<label for="meta-textarea" class="prfx-row-title"><?php _e( 'Example Textarea Input', 'prfx-textdomain' )?></label>
<textarea name="meta-textarea" id="meta-textarea"><?php if ( isset ( $prfx_stored_meta['meta-textarea'] ) ) echo $prfx_stored_meta['meta-textarea'][0]; ?></textarea>
</p>
<!-- CHECKBOXES -->
<p>
<span class="prfx-row-title"><?php _e( 'Example Checkbox Input', 'prfx-textdomain' )?></span>
<div class="prfx-row-content">
<label for="meta-checkbox">
<input type="checkbox" name="meta-checkbox" id="meta-checkbox" value="yes" <?php if ( isset ( $prfx_stored_meta['meta-checkbox'] ) ) checked( $prfx_stored_meta['meta-checkbox'][0], 'yes' ); ?> /><?php _e( 'Checkbox label', 'prfx-textdomain' )?>
</label>
<label for="meta-checkbox-two">
<input type="checkbox" name="meta-checkbox-two" id="meta-checkbox-two" value="yes" <?php if ( isset ( $prfx_stored_meta['meta-checkbox-two'] ) ) checked( $prfx_stored_meta['meta-checkbox-two'][0], 'yes' ); ?> /><?php _e( 'Another checkbox', 'prfx-textdomain' )?>
</label>
</div>
</p>
</div>
<?php
}
global $post;
function faq_meta_save( $post_id ) {
global $post;
$post_id= $post->ID;
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
$is_valid_nonce = ( isset( $_POST[ 'faqs_questions_nonce' ] ) && wp_verify_nonce( $_POST['faqs_questions_nonce'],basename(__FILE__)) )? 'true' : 'false';
if ( $is_autosave || $is_revision || !$is_valid_nonce )
{return;} //exit
if( isset( $_POST[ 'meta-select' ] ) )
{ update_post_meta( $post_id, 'meta-select', $_POST[ 'meta-select' ] ); }
if( isset( $_POST[ 'meta-textarea' ] ) ) {
update_post_meta( $post_id, 'meta-textarea', sanitize_text_field($_POST[ 'meta-textarea' ]) ); }
// Checks for input and saves
if( isset( $_POST[ 'meta-checkbox' ] ) ) {
update_post_meta( $post_id, 'meta-checkbox', 'yes' );}
else {
update_post_meta( $post_id, 'meta-checkbox', '' ); }
// Checks for input and saves
if( isset( $_POST[ 'meta-checkbox-two' ] ) ) {
update_post_meta( $post_id, 'meta-checkbox-two', 'yes' );}
else {
update_post_meta( $post_id, 'meta-checkbox-two', '' ); }
}
add_action('save_post','faq_meta_save');

You have to check if you have the meta_key duplicated in the database for the same post_id. Also, I recommend you to use underscores instead of hyphens in the meta_key names. Try this code where the meta_data of the post_id is deleted and then is added the new value.
Try this:
<?php
function faq_manage_things($post)
{
global $post;
$post_id= $post->ID;
wp_nonce_field(basename(__FILE__),'faqs_questions_nonce');
$faq_stored_meta= get_post_meta($post->ID);
?>
<div class="wrap">
<p>
<label for="meta-select" class="prfx-row-title"><?php _e( 'Example Select Input', 'prfx-textdomain' )?></label>
<select name="meta-select" id="meta-select">
<option value="select-one" <?php if ( isset ( $prfx_stored_meta['meta_select'] ) ) selected( $prfx_stored_meta['meta_select'][0], 'select-one' ); ?>><?php _e( 'One', 'prfx-textdomain' )?></option>';
<option value="select-two" <?php if ( isset ( $prfx_stored_meta['meta_select'] ) ) selected( $prfx_stored_meta['meta_select'][0], 'select-two' ); ?>><?php _e( 'Two', 'prfx-textdomain' )?></option>';
</select>
</p>
<!-- TEXT AREA -->
<p>
<label for="meta-textarea" class="prfx-row-title"><?php _e( 'Example Textarea Input', 'prfx-textdomain' )?></label>
<textarea name="meta-textarea" id="meta-textarea"><?php if ( isset ( $prfx_stored_meta['meta_textarea'] ) ) echo $prfx_stored_meta['meta_textarea'][0]; ?></textarea>
</p>
<!-- CHECKBOXES -->
<p>
<span class="prfx-row-title"><?php _e( 'Example Checkbox Input', 'prfx-textdomain' )?></span>
<div class="prfx-row-content">
<label for="meta-checkbox">
<input type="checkbox" name="meta-checkbox" id="meta-checkbox" value="yes" <?php if ( isset ( $prfx_stored_meta['meta_checkbox'] ) ) checked( $prfx_stored_meta['meta_checkbox'][0], 'yes' ); ?> /><?php _e( 'Checkbox label', 'prfx-textdomain' )?>
</label>
<label for="meta-checkbox-two">
<input type="checkbox" name="meta-checkbox-two" id="meta-checkbox-two" value="yes" <?php if ( isset ( $prfx_stored_meta['meta_checkbox_two'] ) ) checked( $prfx_stored_meta['meta_checkbox_two'][0], 'yes' ); ?> /><?php _e( 'Another checkbox', 'prfx-textdomain' )?>
</label>
</div>
</p>
</div>
<?php
}
global $post;
function faq_meta_save( $post_id ) {
global $post;
$post_id= $post->ID;
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
$is_valid_nonce = ( isset( $_POST[ 'faqs_questions_nonce' ] ) && wp_verify_nonce( $_POST['faqs_questions_nonce'],basename(__FILE__)) )? 'true' : 'false';
if ( $is_autosave || $is_revision || !$is_valid_nonce )
{return;} //exit
if( isset( $_POST[ 'meta-select' ] ) ) {
remove_post_meta( $post_id, 'meta_select', $_POST[ 'meta-select' ] );
add_post_meta( $post_id, 'meta_select', $_POST[ 'meta-select' ] );
}
if( isset( $_POST[ 'meta-textarea' ] ) ) {
remove_post_meta( $post_id, 'meta_textarea', sanitize_text_field($_POST[ 'meta-textarea' ]) );
add_post_meta( $post_id, 'meta_textarea', sanitize_text_field($_POST[ 'meta-textarea' ]) );
}
// Checks for input and saves
if( isset( $_POST[ 'meta-checkbox' ] ) ) {
remove_post_meta( $post_id, 'meta_checkbox', 'yes' );
add_post_meta( $post_id, 'meta_checkbox', 'yes' );
}
else {
remove_post_meta( $post_id, 'meta_checkbox');
}
// Checks for input and saves
if( isset( $_POST[ 'meta-checkbox-two' ] ) ) {
remove_post_meta( $post_id, 'meta_checkbox-two', 'yes' );
add_post_meta( $post_id, 'meta_checkbox-two', 'yes' );
}
else {
remove_post_meta( $post_id, 'meta_checkbox-two');
}
}
add_action('save_post','faq_meta_save');

Related

PHP/Dokan/WooCommerce. Change input type="text" to input="checkbox"

We have a WordPress site using Dokan.
I'd like to add a checkbox where the user can check whether the product should be a donation.
I got this snippet that I'm trying to modify. My PHP is a bit too basic. Please help.
/*
* 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">
<input type="text" class="dokan-form-control" name="new_field" placeholder="<?php esc_attr_e( 'Product Code', 'dokan-lite' ); ?>">
</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'] );
}
}
/*
* 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">
<input type="hidden" name="new_field" id="dokan-edit-product-id" value="<?php echo esc_attr( $post_id ); ?>"/>
<label for="new_field" class="form-label"><?php esc_html_e( 'Product Code', 'dokan-lite' ); ?></label>
<?php dokan_post_input_box( $post_id, 'new_field', array( 'placeholder' => __( 'product code', 'dokan-lite' ), 'value' => $new_field ) ); ?>
<div class="dokan-product-title-alert dokan-hide">
<?php esc_html_e( 'Please enter product code!', 'dokan-lite' ); ?>
</div>
</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 ) ) {
?>
<span class="details"><?php echo esc_attr__( 'Product Code:', 'dokan-lite' ); ?> <strong><?php echo esc_attr( $new_field ); ?></strong></span>
<?php
}
}
This is how far I got:
/*
* 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">
<input type="checkbox" class="dokan-form-control" name="new_field" placeholder="<?php esc_attr_e( 'Product Code', 'dokan-lite' ); ?>">
</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'] );
}
}
/*
* 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">
<input type="hidden" name="new_field" id="dokan-edit-product-id" value="<?php echo esc_attr( $post_id ); ?>"/>
<label for="new_field" class="form-label"><?php esc_html_e( 'Product Code', 'dokan-lite' ); ?></label>
<?php dokan_post_input_box( $post_id, 'new_field', array( 'placeholder' => __( 'product code', 'dokan-lite' ), 'value' => $new_field ) ); ?>
<div class="dokan-product-title-alert dokan-hide">
<?php esc_html_e( 'Please enter product code!', 'dokan-lite' ); ?>
</div>
</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 ) ) {
?>
<span class="details"><?php echo esc_attr__( 'Donation Product', 'dokan-lite' ); ?> <strong><?php echo esc_attr( $new_field ); ?></strong></span>
<?php
}
}
The rest I'm struggling with. Many thanks for any help on this.

Be able to select multiple values in "select" or "checkbox" wordpress

How to select multiple values in listbox. I have tried with the below code, it selects the value only once. Please suggest and provide an alternative way to select the multiple values at the time:
I work with wordpress, this is my code:
// Add metabox
add_action( 'add_meta_boxes', 'cpt_news_filiale_meta_box_add' );
function cpt_news_filiale_meta_box_add()
{
add_meta_box( 'gps-meta-box-id', 'Filiale', 'cpt_entreprise_news_filiale_meta_box_display', 'newsdesfiliales', 'normal', 'high' );
}
// Dislay metabox
function cpt_entreprise_news_filiale_meta_box_display( $post )
{
$args = array(
'numberposts' => 999,
'post_type' => 'entreprise_sector',
'status' => 'publish',
'suppress_filters' => 0,
);
$entreprises = get_posts( $args );
$values = get_post_custom( $post->ID );
$text = isset( $values['filiale_referente[]'] ) ? esc_attr( $values['filiale_referente'][0] ) : '';
?>
<p>
<label for="filiale_referente">Filiale référente : </label>
<select name='filiale_referente' id='filiale_referente' multiple>
<?php foreach ($entreprises as $entreprise): ?>
<option <?php if($text == $entreprise->ID ) :?> selected="true" <?php endif;?>value="<?php echo esc_attr($entreprise->ID); ?>"><?php echo esc_html($entreprise->post_title); ?></option>
<?php endforeach; ?>
</select>
</p>
<?php
}
// Save metabox
add_action( 'save_post', 'cpt_news_filiale_meta_box_save' );
function cpt_news_filiale_meta_box_save( $post_id )
{
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
if( !current_user_can( 'edit_post', $post_id ) ) return;
if( isset( $_POST['filiale_referente'] ) )
update_post_meta( $post_id, 'filiale_referente', wp_kses( $_POST['filiale_referente'] ) );
}
Try this code
// Add metabox
add_action( 'add_meta_boxes', 'cpt_news_filiale_meta_box_add' );
function cpt_news_filiale_meta_box_add()
{
add_meta_box( 'gps-meta-box-id', 'Filiale', 'cpt_entreprise_news_filiale_meta_box_display', 'newsdesfiliales', 'normal', 'high' );
}
// Dislay metabox
function cpt_entreprise_news_filiale_meta_box_display( $post )
{
$args = array(
'numberposts' => 999,
'post_type' => 'entreprise_sector',
'status' => 'publish',
'suppress_filters' => 0,
);
$entreprises = get_posts( $args );
$values = get_post_meta( $post->ID,'filiale_referente', true);
$valuesArr = explode(",",$values);
?>
<p>
<label for="filiale_referente">Filiale référente : </label>
<select name='filiale_referente[]' id='filiale_referente' multiple>
<?php foreach ($entreprises as $entreprise): ?>
<option <?php if( in_array($entreprise->ID,$valuesArr)) :?> selected="true" <?php endif;?>value="<?php echo esc_attr($entreprise->ID); ?>"><?php echo esc_html($entreprise->post_title); ?></option>
<?php endforeach; ?>
</select>
</p>
<?php
}
// Save metabox
add_action( 'save_post', 'cpt_news_filiale_meta_box_save' );
function cpt_news_filiale_meta_box_save( $post_id )
{
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
if( !current_user_can( 'edit_post', $post_id ) ) return;
if( isset( $_POST['filiale_referente'] ) )
update_post_meta( $post_id, 'filiale_referente', implode(",",$_POST['filiale_referente']) );
}

Wordpress - Custom post image on frontend doesn't upload

I've one form to upload an attachment file
<form id="post-job-form" class="frontend-form" action="" method="post" enctype="multipart/form-data" role="form">
<?php
$status_message = '';
if( isset( $_GET['message'] ) ){
$status_message = $_GET['message'];
}
// check if user have post a company
$check = get_posts( array( 'post_type' => 'company', 'author' => get_current_user_id() ) );
if( $check == null ){
$status_message = '6';
}//endif;
jobboard_set_post_message( $status_message );
?>
<div class="form-group">
<label for="sallary_periode"><?php _e( 'Salaire Periode', 'jobboard' ); ?></label>
<select name="sallary_periode" id="sallary_periode" class="form-control">
<?php
$sallary_periode = array(
'hourly' => 'Hourly',
'daily' => 'Daily',
'weekly' => 'Weekly',
'monthly' => 'Monthly'
);
foreach( $sallary_periode as $periode_key => $periode_value ) {
$selected = '';
if( $default['sallary_periode'] == $periode_key ){
$selected = 'selected';
}
echo '<option value="'.$periode_key.'" '.$selected.'>'.esc_attr($periode_value).'</option>';
}
?>
</select>
</div><!-- /.form-group -->
<div class="form-group">
<label for="job_img"><?php _e( 'L`image (en option)', 'jobboard' ); ?></label>
<?php
if( isset($_GET['action']) && $_GET['action'] == 'edit' ){
$edit = get_post( $_GET['jid'] );
$jobimag = get_post_meta( $edit->ID, 'jbchild_meta_job_image', true );
if(!empty($jobimag)){
echo '<img src="' . $jobimag . '">';
}//!empty
}//endif;
?>
<input class="" type="file" name="job_photo" id="job_photo" accept="image/*" />
<span class="help-block"><?php _e( 'Télécharger éventuellement votre image pour les candidats pour voir', 'jobboard' ); ?></span>
</div><!-- /.form-group -->
<?php
if( isset( $_GET['action'] ) && $_GET['action'] == 'edit' ){
$button_text = __( 'Update Job', 'jobboard' );
?>
<input type="hidden" name="form_type" id="form_type" value="edit_post_job" />
<input type="hidden" name="post_id" id="post_id" value="<?php echo esc_attr( $default['post_id'] ); ?>" />
<?php
}else{
$button_text = __( 'Post A Job', 'jobboard' );
?>
<input type="hidden" name="form_type" id="form_type" value="post_job" />
<?php
}
?>
<input type="hidden" name="user_id" id="user_id" value="<?php echo esc_attr( get_current_user_id() ); ?>" />
<button type="submit" name="submit" class="btn btn-post-resume"><?php echo esc_attr( $button_text ); ?></button>
</form>
And this is my function:
function jobboard_post_job_123( $data = array(), $files = array(), $update = false ){
$post_status = 'publish';
if(jobboard_option('enable_highlight_package_job') == '1'){
$post_status ='publish';
}
$job_args = array(
'post_content' => $data['job_description'],
'post_title' => $data['job_title'],
'post_status' => $post_status,
'post_type' => 'job',
'post_author' => $data['user_id'],
);
$message = '1';
if( $update ){
$job_args['ID'] = $data['post_id'];
$job_args['post_status'] = get_post_status( $data['post_id'] );
$message = '2';
}
$job_id = wp_insert_post( $job_args );
if($job_id){
if( isset( $data['job_region'] ) ){
wp_set_object_terms( $job_id, $data['job_region'], 'job_region' );
}
if( isset( $data['job_type'] ) ){
wp_set_object_terms( $job_id, $data['job_type'], 'job_type' );
}
if( isset( $data['job_category'] ) ){
wp_set_object_terms( $job_id, $data['job_category'], 'job_category' );
}
// Job Company Metabox
update_post_meta( $job_id, '_jboard_job_company', $data['job_company'] );
// Job Experience Metabox
update_post_meta( $job_id, '_jboard_job_experiences', $data['job_experience'] );
// Job Salary Metabox
update_post_meta( $job_id, '_jboard_job_sallary', $data['job_sallary'] );
// Job Salary Periode
update_post_meta( $job_id, '_jboard_sal_periode', $data['sallary_periode'] );
// Job Summary Metabox
update_post_meta( $job_id, '_jboard_job_summary', $data['job_summary'] );
// Job Overview Metabox
update_post_meta( $job_id, '_jboard_job_overview', $data['job_overview'] );
if( !empty( $files['job_photo']['name'] ) ){
$job_img = jobboard_file_upload( $files['job_photo'], 'file' );
$old_job_img = get_post_meta( $job_id, 'jbchild_meta_job_image', true );
if($job_img){
//update_post_meta( $job_id, 'jbchild_meta_job_image', $job_img['url'], $old_job_img );
update_post_meta( $job_id, 'jbchild_meta_job_image', 'http://www.soslivreur.fr/wp-content/uploads/2016/04/20160316_174725.jpg' );
}
}
// Job metabox data set
$job_meta = array(
'_jboard_sal_periode'
);
update_post_meta( $job_id, 'jobboard_job_mb_fields', $job_meta );
wp_redirect( esc_url(add_query_arg( array( 'action' => 'edit', 'jid' => $job_id, 'message' => $message ) ) ) );
exit;
}
}
I have a problem. When I'm submitting this form others field can insert to database but an image can't insert to database.
How to fix my code? Thank you
please replace this line of code in your function file function name is jobboard_post_job_123
if( !empty( $files['job_photo']['name'] ) ){
$job_img = jobboard_file_upload( $files['job_photo'], 'file' );
//$old_job_img = get_post_meta( $job_id, 'jbchild_meta_job_image', true );
if($job_img != ''){
update_post_meta( $job_id, 'jbchild_meta_job_image', 'http://www.soslivreur.fr/wp-content/uploads/2016/04/20160316_174725.jpg' );
}
}
And then check it's work or not becuase you had predefine Old job image on that.

Second excerpt in Wordpress

I have created second excerpt in Wordpress with following code.
add_action( 'admin_menu', 'my_create_post_meta_box' );
add_action( 'save_post', 'my_save_post_meta_box', 10, 2 );
function my_create_post_meta_box() {
add_meta_box( 'my-meta-box', 'Second Excerpt', 'my_post_meta_box', 'post', 'normal', 'high' );
}
function my_post_meta_box( $object, $box ) { ?>
<p>
<?php if ( current_user_can( 'upload_files' ) ) : ?>
<div id="media-buttons" class="hide-if-no-js">
<?php do_action( 'media_buttons' ); ?>
</div>
<?php endif; ?>
<br />
<label for="second-excerpt">Second Excerpt With Images for Post List Page</label>
<textarea name="second-excerpt" id="second-excerpt" cols="60" rows="4" tabindex="30" style="width: 97%;"><?php echo wp_specialchars( get_post_meta( $object->ID, 'Second Excerpt', true ), 1 ); ?></textarea>
<input type="hidden" name="my_meta_box_nonce" value="<?php echo wp_create_nonce( plugin_basename( __FILE__ ) ); ?>" />
</p>
<?php }
function my_save_post_meta_box( $post_id, $post ) {
if ( !wp_verify_nonce( $_POST['my_meta_box_nonce'], plugin_basename( __FILE__ ) ) )
return $post_id;
if ( !current_user_can( 'edit_post', $post_id ) )
return $post_id;
$meta_value = get_post_meta( $post_id, 'Second Excerpt', true );
$new_meta_value = stripslashes( $_POST['second-excerpt'] );
if ( $new_meta_value && '' == $meta_value )
add_post_meta( $post_id, 'Second Excerpt', $new_meta_value, true );
elseif ( $new_meta_value != $meta_value )
update_post_meta( $post_id, 'Second Excerpt', $new_meta_value );
elseif ( '' == $new_meta_value && $meta_value )
delete_post_meta( $post_id, 'Second Excerpt', $meta_value );
}
Now, How will I be able to display it instead of the entire post content? My wordpress home page shows latest posts instead of any static page.
You'll want to use get_post_meta() for that:
echo get_post_meta( get_the_ID(), 'Second Excerpt', true );
If you're wanting to replace the post content with this second excerpt, you'll need to write a custom the_content filter.

Populating custom fields on checkout page

I have created two plugins:
To add 3 custom fields on register form
To add this 3 custom fields on checkout page and user dashboard panel.
I have successfuly added my fields in register form, checkout page and user dashboar panel but on checkout page I cannot populate them with the presaved values.
First plugin is for adding new fields in registration. The new fields are: 'billing_bulstat' ; 'billing_mol' and 'billing_adres'. They are succesfuly saved and displayed in user dashboard panel. The code is:
<?php
/**
* Plugin Name: WooCommerce Registration Fields in Luga.bg - Traders Store
* Plugin URI: http://www.luga.bg/traders
* Description: My Custom registration fields in Luga.bg - Traders Store
* Version: 2.0
* Author: Nikolay Grudev
* Author URI: http://www.luga.bg/traders
* License: GPL3
*/
/**
* Add new register fields for WooCommerce registration in Luga.bg - Traders Store.
*
* #return string Register fields HTML.
*/
function wooc_extra_register_fields() {
?>
<p class="form-row form-row-first">
<label for="reg_billing_first_name"><?php _e( 'First name', 'woocommerce' ); ?> <span
class="required">*</span></label>
<input type="text" class="input-text" name="billing_first_name" id="reg_billing_first_name" value="<?php if ( !
empty( $_POST['billing_first_name'] ) ) esc_attr_e( $_POST['billing_first_name'] ); ?>" />
</p>
<p class="form-row form-row-last">
<label for="reg_billing_last_name"><?php _e( 'Last name', 'woocommerce' ); ?> <span
class="required">*</span></label>
<input type="text" class="input-text" name="billing_last_name" id="reg_billing_last_name" value="<?php if ( !
empty( $_POST['billing_last_name'] ) ) esc_attr_e( $_POST['billing_last_name'] ); ?>" />
</p>
<div class="clear"></div>
<p class="form-row form-row-wide">
<label for="reg_billing_company"><?php _e( 'Име на фирмата', 'woocommerce' ); ?> <span
class="required">*</span></label>
<input type="text" class="input-text" name="billing_company" id="reg_billing_company" value="<?php if ( ! empty(
$_POST['billing_company'] ) ) esc_attr_e( $_POST['billing_company'] ); ?>" />
</p>
<div class="clear"></div>
<p class="form-row form-row-first">
<label for="reg_billing_bulstat"><?php _e( 'ЕИК', 'woocommerce' ); ?> <span class="required">*</span></label>
<input type="text" class="input-text" name="billing_bulstat" id="reg_billing_bulstat" value="<?php if ( ! empty(
$_POST['billing_bulstat'] ) ) esc_attr_e( $_POST['billing_bulstat'] ); ?>" />
</p>
<p class="form-row form-row-last">
<label for="reg_billing_city"><?php _e( 'City', 'woocommerce' ); ?> <span class="required">*</span></label>
<input type="text" class="input-text" name="billing_city" id="reg_billing_city" value="<?php if ( ! empty(
$_POST['billing_city'] ) ) esc_attr_e( $_POST['billing_city'] ); ?>" />
</p>
<p class="form-row form-row-wide">
<label for="reg_billing_mol"><?php _e( 'МОЛ (Материално отговорно лице)', 'woocommerce' ); ?> <span
class="required">*</span></label>
<input type="text" class="input-text" name="billing_mol" id="reg_billing_mol" value="<?php if ( ! empty( $_POST
['billing_mol'] ) ) esc_attr_e( $_POST['billing_mol'] ); ?>" />
</p>
<p class="form-row form-row-wide">
<label for="reg_billing_adres"><?php _e( 'Адрес за фактуриране', 'woocommerce' ); ?> <span
class="required">*</span></label>
<input type="text" class="input-text" name="billing_adres" id="reg_billing_adres" value="<?php if ( ! empty(
$_POST['billing_adres'] ) ) esc_attr_e( $_POST['billing_adres'] ); ?>" />
</p>
<?php
}
add_action( 'woocommerce_register_form_start', 'wooc_extra_register_fields' );
/**
* Validate the extra register fields.
*
* #param string $username Current username.
* #param string $email Current email.
* #param object $validation_errors WP_Error object.
*
* #return void
*/
function wooc_validate_extra_register_fields( $username, $email, $validation_errors ) {
if ( isset( $_POST['billing_first_name'] ) && empty( $_POST['billing_first_name'] ) ) {
$validation_errors->add( 'billing_first_name_error', __( '<strong>Грешка</strong>: Първото име е
задъжлително!', 'woocommerce' ) );
}
if ( isset( $_POST['billing_last_name'] ) && empty( $_POST['billing_last_name'] ) ) {
$validation_errors->add( 'billing_last_name_error', __( '<strong>Грешка</strong>: Фамилията е
задължителна!.', 'woocommerce' ) );
}
if ( isset( $_POST['billing_company'] ) && empty( $_POST['billing_company'] ) ) {
$validation_errors->add( 'billing_company_error', __( '<strong>Грешка</strong>: Името на фирмата е
задължително!.', 'woocommerce' ) );
}
if ( isset( $_POST['billing_bulstat'] ) && empty( $_POST['billing_bulstat'] ) ) {
$validation_errors->add( 'billing_bulstat_error', __( '<strong>Грешка</strong>: ЕИК на фирмата е
задължителен!.', 'woocommerce' ) );
}
if ( isset( $_POST['billing_city'] ) && empty( $_POST['billing_city'] ) ) {
$validation_errors->add( 'billing_city_error', __( '<strong>Грешка</strong>: Градът е задължителен!.',
'woocommerce' ) );
}
if ( isset( $_POST['billing_mol'] ) && empty( $_POST['billing_mol'] ) ) {
$validation_errors->add( 'billing_mol_error', __( '<strong>Грешка</strong>: МОЛ е задължително!.',
'woocommerce' ) );
}
if ( isset( $_POST['billing_adres'] ) && empty( $_POST['billing_adres'] ) ) {
$validation_errors->add( 'billing_adres_error', __( '<strong>Грешка</strong>: Адресът за фактуриране е
задължителен!.', 'woocommerce' ) );
}
}
add_action( 'woocommerce_register_post', 'wooc_validate_extra_register_fields', 10, 3 );
/**
* Save the extra register fields.
*
* #param int $customer_id Current customer ID.
*
* #return void
*/
function wooc_save_extra_register_fields( $customer_id ) {
if ( isset( $_POST['billing_first_name'] ) ) {
// WordPress default first name field.
update_user_meta( $customer_id, 'first_name', sanitize_text_field( $_POST['billing_first_name'] ) );
// WooCommerce billing first name.
update_user_meta( $customer_id, 'billing_first_name', sanitize_text_field( $_POST['billing_first_name'] ) );
}
if ( isset( $_POST['billing_last_name'] ) ) {
// WordPress default last name field.
update_user_meta( $customer_id, 'last_name', sanitize_text_field( $_POST['billing_last_name'] ) );
// WooCommerce billing last name.
update_user_meta( $customer_id, 'billing_last_name', sanitize_text_field( $_POST['billing_last_name'] ) );
}
if ( isset( $_POST['billing_company'] ) ) {
// WooCommerce company name
update_user_meta( $customer_id, 'company', sanitize_text_field( $_POST['billing_company'] ) );
// WooCommerce billing company name.
update_user_meta( $customer_id, 'billing_company', sanitize_text_field( $_POST['billing_company'] ) );
}
if ( isset( $_POST['billing_bulstat'] ) ) {
// WooCommerce company bulstat
update_user_meta( $customer_id, 'bulstat', sanitize_text_field( $_POST['billing_bulstat'] ) );
// WooCommerce billing company bulstat
update_user_meta( $customer_id, 'billing_bulstat', sanitize_text_field( $_POST['billing_bulstat'] ) );
}
if ( isset( $_POST['billing_city'] ) ) {
// WooCommerce company city
update_user_meta( $customer_id, 'city', sanitize_text_field( $_POST['billing_city'] ) );
// WooCommerce billing company city
update_user_meta( $customer_id, 'billing_city', sanitize_text_field( $_POST['billing_city'] ) );
}
if ( isset( $_POST['billing_mol'] ) ) {
// WooCommerce company mol
update_user_meta( $customer_id, 'mol', sanitize_text_field( $_POST['billing_mol'] ) );
// WooCommerce billing company mol
update_user_meta( $customer_id, 'billing_mol', sanitize_text_field( $_POST['billing_mol'] ) );
}
if ( isset( $_POST['billing_adres'] ) ) {
// WooCommerce company address
update_user_meta( $customer_id, 'adres', sanitize_text_field( $_POST['billing_adres'] ) );
// WooCommerce billing company address
update_user_meta( $customer_id, 'billing_adres', sanitize_text_field( $_POST['billing_adres'] ) );
}
}
add_action( 'woocommerce_created_customer', 'wooc_save_extra_register_fields' );
add_action( 'woocommerce_checkout_process', 'ws_billing_fields_save', 10, 1 );
function ws_billing_fields_save( $user_id ){
if ( isset( $_POST['billing_bulstat'] ) ) {
update_user_meta($user_id, 'billing_bulstat', $_POST['billing_bulstat']);
}
if ( isset( $_POST['billing_mol'] ) ) {
update_user_meta($user_id, 'billing_mol', $_POST['billing_mol']);
}
if ( isset( $_POST['billing_adres'] ) ) {
update_user_meta($user_id, 'billing_adres', $_POST['billing_adres']);
}
}
/**
* Dopylnitelni poleta v User Profil na Dashboard v Wordpress
*/
function eri_add_custom_user_profile_fields( $user ) {
?>
<!-- Field Title -->
<h3><?php _e('Company Information', 'eribootstrap'); ?></h3>
<table class="form-table">
<tr>
<th>
<label for="billing_bulstat">
<?php _e('ЕИК', 'eribootstrap'); ?>
</label>
</th>
<td>
<input type="text" name="billing_bulstat" id="billing_bulstat" value="<?php echo
esc_attr( get_the_author_meta( 'billing_bulstat', $user->ID ) ); ?>" class="regular-text" /><br />
<span class="description"><?php _e('Въведи ЕИК.', 'eribootstrap'); ?></span>
</td>
</tr><!-- field ends here -->
<tr>
<th>
<label for="billing_mol"><?php _e('МОЛ', 'eribootstrap'); ?>
</label></th>
<td>
<input type="text" name="billing_mol" id="billing_mol" value="<?php echo esc_attr(
get_the_author_meta( 'billing_mol', $user->ID ) ); ?>" class="regular-text" /><br />
<span class="description"><?php _e('Въведете МОЛ на фирмата', 'eribootstrap'); ?
></span>
</td>
</tr><!-- field ends here -->
<tr>
<th>
<label for="billing_adres"><?php _e('Адрес за фактуриране', 'eribootstrap'); ?>
</label></th>
<td>
<textarea name="billing_adres" id="billing_adres" class="regular-text"><?php echo esc_attr( get_the_author_meta(
'billing_adres', $user->ID ) ); ?>
</textarea><br />
<span class="description"><?php _e('Въведете адрес за фактуриране', 'eribootstrap'); ?></span>
</td>
</tr><!-- field ends here -->
</table>
<?php }
function eri_save_custom_user_profile_fields( $user_id ) {
if ( !current_user_can( 'edit_user', $user_id ) )
return FALSE;
// Update and Save Field
update_usermeta( $user_id, 'billing_bulstat', $_POST['billing_bulstat'] );
update_usermeta( $user_id, 'billing_mol', $_POST['billing_mol'] );
update_usermeta( $user_id, 'billing_adres', $_POST['billing_adres'] );
}
add_action( 'show_user_profile', 'eri_add_custom_user_profile_fields' );
add_action( 'edit_user_profile', 'eri_add_custom_user_profile_fields' );
add_action( 'personal_options_update', 'eri_save_custom_user_profile_fields' );
add_action( 'edit_user_profile_update', 'eri_save_custom_user_profile_fields' );
The second plugin adds three new custom field on checkout page. They are displayed, but are not automaticaly populated. I use $checkout->get_value( 'my_field_name' ) ); function, but is doesn't work.
I want they to be automatic populated with the presaved values. The fields are the same: 'billing_bulstat' ; 'billing_mol' and 'billing_adres'. The code is:
<?php
/*
Plugin Name: Woocommerce Checkout fileds
Plugin URI: https://www.luga.bg/traders
Description: Customized Woocommerce checkout fields
Version: 1
Author: Nikolay Grudev
Author URI: http://www.luga.bg/
*/
/**
* set customized Woocommerce checkout fields
*/
add_filter( 'woocommerce_checkout_fields' , 'customize_fields' );
function customize_fields( $fields ) {
// make fields required:
$fields['billing']['billing_company']['required'] = true;
return $fields;
}
// Remove some checkout billing fields
function kia_filter_billing_fields($fields){
unset( $fields["billing_country"] );
unset( $fields["billing_address_1"] );
unset( $fields["billing_address_2"] );
unset( $fields["billing_state"] );
unset( $fields["billing_postcode"] );
return $fields;
}
add_filter( 'woocommerce_billing_fields', 'kia_filter_billing_fields' );
/**
* Add the field to the checkout
*/
add_action( 'woocommerce_after_order_notes', 'my_custom_checkout_field' );
function my_custom_checkout_field( $checkout ) {
echo '<div id="my_custom_checkout_field"><h2>' . __('Extra Information') . '</h2>';
woocommerce_form_field(
'billing_bulstat', array(
'type' => 'text',
'class' => array('my-field-class form-row-wide'),
'label' => __('EIK'),
'placeholder' => __('Enter something'),
'required' => true,
),$checkout->get_value( 'billing_bulstat' ) );
woocommerce_form_field(
'billing_mol', array(
'type' => 'text',
'class' => array('my-field-class form-row-wide'),
'label' => __('MOL'),
'placeholder' => __('Enter something'),
'required' => true,
), $checkout->get_value( 'billing_mol' ) );
woocommerce_form_field(
'billing_adres', array(
'type' => 'text',
'class' => array('my-field-class form-row-wide'),
'label' => __('Adres za fakturirane'),
'placeholder' => __('Enter something'),
'required' => true,
), $checkout->get_value( 'billing_adres' ) );
echo '</div>';
}
/**
* Validate the custom field.
*/
add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');
function my_custom_checkout_field_process() {
// Check if set, if its not set add an error.
if ( ! $_POST['billing_bulstat'] )
wc_add_notice( __( 'Please enter something into this new shiny field.' ), 'error' );
if ( ! $_POST['billing_mol'] )
wc_add_notice( __( 'Please enter something into this new shiny field.' ), 'error' );
if ( ! $_POST['billing_adres'] )
wc_add_notice( __( 'Please enter something into this new shiny field.' ), 'error' );
}
/**
* Save 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 ( ! empty( $_POST['billing_bulstat'] ) ) {
update_post_meta( $order_id, 'billing_bulstat', sanitize_text_field( $_POST['billing_bulstat'] ) );
}
if ( ! empty( $_POST['billing_mol'] ) ) {
update_post_meta( $order_id, 'billing_mol', sanitize_text_field( $_POST['billing_mol'] ) );
}
if ( ! empty( $_POST['billing_adres'] ) ) {
update_post_meta( $order_id, 'billing_adres', sanitize_text_field( $_POST['billing_adres'] ) );
}
}
/**
* 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){
echo '<p><strong>'.__('Extra Information').':</strong> ' . get_post_meta( $order->id, 'billing_bulstat', true )
. '</p>';
echo '<p><strong>'.__('Extra Information').':</strong> ' . get_post_meta( $order->id, 'billing_mol', true ) .
'</p>';
echo '<p><strong>'.__('Extra Information').':</strong> ' . get_post_meta( $order->id, 'billing_adres', true ) .
'</p>';
}
// display the extra data on order recieved page and my-account order review
function kia_display_order_data( $order_id ){ ?>
<h2><?php _e( 'Additional Info' ); ?></h2>
<table class="shop_table shop_table_responsive additional_info">
<tbody>
<tr>
<th><?php _e( 'Bulstat: ' ); ?></th>
<td><?php echo get_post_meta( $order_id, 'billing_bulstat', true ); ?></td>
</tr>
<tr>
<th><?php _e( 'MOL: ' ); ?></th>
<td><?php echo get_post_meta( $order_id, 'billing_mol', true ); ?></td>
</tr>
<tr>
<th><?php _e( 'Adres za fakturirane: ' ); ?></th>
<td><?php echo get_post_meta( $order_id, 'billing_adres', true ); ?></td>
</tr>
</tbody>
</table>
<?php }
add_action( 'woocommerce_thankyou', 'kia_display_order_data', 20 );
add_action( 'woocommerce_view_order', 'kia_display_order_data', 20 );
// display the extra data in the order admin panel
function kia_display_order_data_in_admin( $order ){ ?>
<div class="order_data_column">
<h4><?php _e( 'Danni za firmata', 'woocommerce' ); ?></h4>
<?php
echo '<p><strong>' . __( 'Firma: ' ) . '</strong>' . get_post_meta( $order->id, '_billing_company', true
) . '</p>';
echo '<p><strong>' . __( 'Bulstat: ' ) . '</strong>' . get_post_meta( $order->id, 'billing_bulstat',
true ) . '</p>';
echo '<p><strong>' . __( 'MOL: ' ) . '</strong>' . get_post_meta( $order->id, 'billing_mol', true ) .
'</p>';
echo '<p><strong>' . __( 'Adres za fakturirane: ' ) . '</strong>' . get_post_meta( $order-
>id, 'billing_adres', true ) . '</p>'; ?>
</div>
<?php }
add_action( 'woocommerce_admin_order_data_after_order_details', 'kia_display_order_data_in_admin' );
// WooCommerce 2.3+
function kia_email_order_meta_fields( $fields, $sent_to_admin, $order ) {
$fields['billing_bulstat'] = array(
'label' => __( 'Bulstat' ),
'value' => get_post_meta( $order->id, 'billing_bulstat', true ),
);
$fields['billing_mol'] = array(
'label' => __( 'MOL' ),
'value' => get_post_meta( $order->id, 'billing_mol', true ),
);
$fields['billing_adres'] = array(
'label' => __( 'Adrez za fakturirane' ),
'value' => get_post_meta( $order->id, 'billing_adres', true ),
);
return $fields;
}
add_filter('woocommerce_email_order_meta_fields', 'kia_email_order_meta_fields', 10, 3 );
?>
Where I am wrong? Why I my fields are not populated atomaticaly with their values?
Thanks for help!
the site is www.luga.bg/traders

Categories