How to set radio buttons in custom meta box checked? - wordpress

I created a custom meta box where you can choose a value from some radio buttons and save it to the post_meta table in the wordpress database. With the following code I save the value:
function save_value_of_my_custom_metabox ($post_id, $post){
$post_id = get_the_ID();
$new_meta_value = ( isset( $_POST['the_name_of_the_radio_buttons'] ) ? sanitize_html_class( $_POST['the_name_of_the_radio_buttons'] ) : '' );
$meta_key = 'my_key';
update_post_meta( $post_id, $meta_key, $new_meta_value );
}
But if the post will be edited again I want the radio button with the current value to set checked. What is the best way to do that? Here is the function to display the meta box:
function my_custom_meta_box( $object, $box ) {
$post_id=get_the_ID();
$key='my_key';
$the_value_that_should_be_set_to_checked=get_post_meta( $post_id, $key);
//$the_value_that_should_be_set_to_checked[0] returns the value as string
?>
<label for="my_custom_metabox"><?php _e( "Choose value:", 'choose_value' ); ?></label>
<br />
<input type="radio" name="the_name_of_the_radio_buttons" value="value1">Value1<br>
<input type="radio" name="the_name_of_the_radio_buttons" value="value2">Value2<br>
<input type="radio" name="the_name_of_the_radio_buttons" value="value3">Value3<br>
<input type="radio" name="the_name_of_the_radio_buttons" value="value4">Value4<br>
<?php
}
I could write something like if(isset($the_value_that_should_be_set_to_checked[0])=="value of that line") echo "checked='checked'"; in every line but that doesn't seem very elegant to me. Using javascript is also pretty complicated in wordpress because I would have to use the hooks, enqueue the script and just for changing the checked property with one line of javascript it's not worth it. What's the best practice for that?

I am assuming that you are trying to add custom meta box for 'Posts'. Below code will work for you. It will show Radio buttons on add new post or edit post screen. Please read the comments in the code. It will help you in understanding the code.
You can use WordPress's checked function to decide whether to select the radio button or not.
Feel free to ask if you have any doubts.
/**
* Adds a box to the main column on the Post add/edit screens.
*/
function wdm_add_meta_box() {
add_meta_box(
'wdm_sectionid', 'Radio Buttons Meta Box', 'wdm_meta_box_callback', 'post'
); //you can change the 4th paramter i.e. post to custom post type name, if you want it for something else
}
add_action( 'add_meta_boxes', 'wdm_add_meta_box' );
/**
* Prints the box content.
*
* #param WP_Post $post The object for the current post/page.
*/
function wdm_meta_box_callback( $post ) {
// Add an nonce field so we can check for it later.
wp_nonce_field( 'wdm_meta_box', 'wdm_meta_box_nonce' );
/*
* Use get_post_meta() to retrieve an existing value
* from the database and use the value for the form.
*/
$value = get_post_meta( $post->ID, 'my_key', true ); //my_key is a meta_key. Change it to whatever you want
?>
<label for="wdm_new_field"><?php _e( "Choose value:", 'choose_value' ); ?></label>
<br />
<input type="radio" name="the_name_of_the_radio_buttons" value="value1" <?php checked( $value, 'value1' ); ?> >Value1<br>
<input type="radio" name="the_name_of_the_radio_buttons" value="value2" <?php checked( $value, 'value2' ); ?> >Value2<br>
<input type="radio" name="the_name_of_the_radio_buttons" value="value3" <?php checked( $value, 'value3' ); ?> >Value3<br>
<input type="radio" name="the_name_of_the_radio_buttons" value="value4" <?php checked( $value, 'value4' ); ?> >Value4<br>
<?php
}
/**
* When the post is saved, saves our custom data.
*
* #param int $post_id The ID of the post being saved.
*/
function wdm_save_meta_box_data( $post_id ) {
/*
* We need to verify this came from our screen and with proper authorization,
* because the save_post action can be triggered at other times.
*/
// Check if our nonce is set.
if ( !isset( $_POST['wdm_meta_box_nonce'] ) ) {
return;
}
// Verify that the nonce is valid.
if ( !wp_verify_nonce( $_POST['wdm_meta_box_nonce'], 'wdm_meta_box' ) ) {
return;
}
// 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_post', $post_id ) ) {
return;
}
// Sanitize user input.
$new_meta_value = ( isset( $_POST['the_name_of_the_radio_buttons'] ) ? sanitize_html_class( $_POST['the_name_of_the_radio_buttons'] ) : '' );
// Update the meta field in the database.
update_post_meta( $post_id, 'my_key', $new_meta_value );
}
add_action( 'save_post', 'wdm_save_meta_box_data' );

I found a working solution but I think this is not how you should do it. Still open for better solutions ;)
This code was added under the php code from above:
if(isset($$the_value_that_should_be_set_to_checked[0])){
$the_value_that_should_be_set_to_checked= $the_value_that_should_be_set_to_checked[0];
}
else{
$the_value_that_should_be_set_to_checked='';
}
Here's the code that I added below the radiobuttons:
<script type="text/javascript">
jQuery(document).ready(function () {
var checked_value= <?php echo json_encode($the_value_that_should_be_set_to_checked);?>;
if(checked_value!==''){
jQuery("input[name=the_name_of_the_radio_buttons][value="+checked_value+"]").attr('checked', 'checked');
}
});
</script>
P.S.: The $ selector will not work but that maybe depends on the theme you use.

Related

How to add default value in custom taxonomy field in wordpress

I've created custom taxonomy name "Front List" using Custom Post Type UI then add a custom field called "Order". I'm trying to set a default value for order. When I create any frontlist using the frontlist panel,
it's adding a default value, but when I create frontlist from "Add Post" page it's not adding any default value for "Order field".
How to I add default value when "Front List" created from "Add Post" page?
This is the code for adding a custom field to Frontlist taxonomy.
<?php
/**
* Adding Custom Field to Taxonomy
* #return void
*/
function frontlists_add_order( $term ) {
?>
<div class="form-field">
<label for="taxOrder"><?php _e( 'Order', 'yourtextdomain' ); ?></label>
<input type="text" name="taxOrder" id="taxOrder" value="">
<p>Your front List item will be sorted by this "Order". The default value is "1".</p>
</div>
<?php
}
add_action( 'frontlists_add_form_fields', 'frontlists_add_order', 10, 2 );
/**
* Adding Custom Field to Taxonomy in Edit Panel
* #return void
*/
function frontlists_edit_order( $term ) {
$term_order = get_term_meta( $term->term_id, 'order', true );
?>
<tr class="form-field">
<th><label for="taxOrder"><?php _e( 'Order', 'yourtextdomain' ); ?></label></th>
<td>
<input type="text" name="taxOrder" id="taxOrder" value="<?php echo esc_attr( $term_order ) ? esc_attr( $term_order ) : ''; ?>">
<p>Your front List item will be sorted by this "Order".</p>
</td>
</tr>
<?php
}
add_action( 'frontlists_edit_form_fields', 'frontlists_edit_order', 10 );
/**
* Saving Custom Field to Taxonomy
*/
function frontlists_save_order( $term_id ) {
if ( isset( $_POST['taxOrder'] ) ) {
$term_order = $_POST['taxOrder'];
if( $term_order ) {
update_term_meta( $term_id, 'order', $term_order );
} else {
update_term_meta( $term_id, 'order', 1 );
}
}
}
add_action( 'edited_frontlists', 'frontlists_save_order' );
add_action( 'create_frontlists', 'frontlists_save_order' );
You can use the created_term action hook to add the new taxonomy term once it's already been added to the database. This action hook is inside the wp_insert_term function. Either put this in your theme (not advised), or inside a plugin.
function so_add_order_field( $term_id, $tt_id, $taxonomy ) {
// The default order value
$default = 1;
// Stop if it's not the right taxonomy
if ( 'frontlists' != $taxonomy ) {
return false;
}
// Get the existing value if exists
$order = get_term_meta( $term_id, 'taxOrder', true );
if ( false === $order ) {
// Add the term meta default
add_term_meta( $term_id, 'taxOrder', $default );
}
}
add_action( 'created_term', 'so_add_order_field', 10, 3 );
Then change the $default value to whatever you'd like it to be. This uses the add_term_meta function which safely adds the meta data to the database for you. Check out the documentation for further info.

Dokan Plugin Customization

I am using dokan plugin for multivendor website. I want to add some extra field in dokan vendor setting page. I use this
add_filter( 'dokan_settings_form_bottom', 'extra_fields', 10, 2);
function extra_fields( $current_user, $profile_info ){
$seller_url= isset( $profile_info['seller_url'] ) ?
$profile_info['seller_url'] : '';?>
<label class="dokan-w3 dokan-control-label" for="setting_address">
<?php _e( 'Website', 'dokan' ); ?>
</label>
<div class="dokan-w5">
<input type="text" class="dokan-form-control input-md valid" name="seller_url" id="reg_seller_url" value="<?php echo $seller_url; ?>" />
</div>
</div>
<?php }
//save the field value
add_action( 'dokan_store_profile_saved', 'save_extra_fields', 15 );
function save_extra_fields( $store_id ) {
if ( isset( $_POST['seller_url'] ) ) {
$dokan_settings = dokan_get_store_info($store_id);
$dokan_settings['seller_url'] = $_POST['seller_url'];
}
update_user_meta( $store_id, 'dokan_profile_settings', $dokan_settings
);
}
But when i use this i am unable to update the payment method.please help me
Thanks
You can try this way to save the filed value and it should solve your problem -
add_action( 'dokan_store_profile_saved', 'save_extra_fields', 15 );
function save_extra_fields( $store_id ) {
$dokan_settings = dokan_get_store_info($store_id);
if ( isset( $_POST['seller_url'] ) ) {
$dokan_settings['seller_url'] = $_POST['seller_url'];
}
update_user_meta( $store_id, 'dokan_profile_settings', $dokan_settings );
}
If the code works then I hope you will mark this topic as resolved!
I have tried this code - https://gist.github.com/nayemDevs/b629d4b1c27c794bdfb729ce6927069e#file-extra-field-php and it is working for me. However, I have checked with Dokan theme and Hestia pro theme. Did you check if there is any theme conflict or not?

Add a checkbox in the post meta box

I want to add a checkbox in product post type. So i wrote the code
add_action( 'add_meta_boxes', 'smashing_add_post_meta_boxes' );
/* Create one or more meta boxes to be displayed on the post editor screen. */
function smashing_add_post_meta_boxes() {
add_meta_box(
'smashing-post-class', // Unique ID
esc_html__( 'Post Class', 'example' ), // Title
'smashing_post_class_meta_box', // Callback function
'product', // Admin page (or post type)
'side', // Context
'default' // Priority
);
}
/* Display the post meta box. */
function smashing_post_class_meta_box( $object, $box ) { ?>
<?php wp_nonce_field( basename( __FILE__ ), 'smashing_post_class_nonce' ); ?>
<p>
<label for="smashing-post-class"><?php _e( "Add a custom CSS class, which will be applied to WordPress' post class.", 'example' ); ?></label>
<br />
<input class="widefat" type="checkbox" name="smashing-post-class" id="smashing-post-class" value="<?php echo esc_attr( get_post_meta( $object->ID, 'smashing_post_class', true ) ); ?>" size="30" />What's New
</p>
<?php }
/* Save post meta on the 'save_post' hook. */
add_action( 'save_post', 'smashing_save_post_class_meta', 10, 2 );
/* Save the meta box's post metadata. */
function smashing_save_post_class_meta( $post_id, $post ) {
/* Verify the nonce before proceeding. */
if ( !isset( $_POST['smashing_post_class_nonce'] ) || !wp_verify_nonce( $_POST['smashing_post_class_nonce'], basename( __FILE__ ) ) )
return $post_id;
/* Get the post type object. */
$post_type = get_post_type_object( $post->post_type );
/* Check if the current user has permission to edit the post. */
if ( !current_user_can( $post_type->cap->edit_post, $post_id ) )
return $post_id;
/* Get the posted data and sanitize it for use as an HTML class. */
$new_meta_value = ( isset( $_POST['smashing-post-class'] ) ? sanitize_html_class( $_POST['smashing-post-class'] ) : '' );
/* Get the meta key. */
$meta_key = 'smashing_post_class';
/* Get the meta value of the custom field key. */
$meta_value = get_post_meta( $post_id, $meta_key, true );
/* If a new meta value was added and there was no previous value, add it. */
if ( $new_meta_value && '' == $meta_value )
add_post_meta( $post_id, $meta_key, $new_meta_value, true );
/* If the new meta value does not match the old value, update it. */
elseif ( $new_meta_value && $new_meta_value != $meta_value )
update_post_meta( $post_id, $meta_key, $new_meta_value );
/* If there is no new meta value but an old value exists, delete it. */
elseif ( '' == $new_meta_value && $meta_value )
delete_post_meta( $post_id, $meta_key, $meta_value );
}
How can i change the code to get the checkbox value and checked if someone check the checkbox before.
Here, i changed only the input box "text" to "checkbox". But i do not know what to do to create a single checkbox. Please help me. I am new in wordpress.
you prob need to assign a value for the checkbox. You might want to think what this value is if not already set.
value="<?php echo esc_attr( get_post_meta( $object->ID, 'smashing_post_class', true ) ); ?>"
on a new post this is not set. So you could do something like
value="<?php if ($x=get_post_meta( $object->ID, 'smashing_post_class', true ) ) {echo $x;}else{echo "whatever";} ?>"
You are already saving the value to post_meta(see $new_meta_value) so the code to set the value already pulls it from the database if it exists.
you might want to rethink the way you are doing the above. The checkbox value is always going to be the same from now on. You might as well set the value to whatever you want it to be right now. E.g.
<input type="checkbox" name="whatever" value="true"> select me for fun
you can access the posted value in your save meta box function
$value= $_POST['whatever'];
and save to post meta (a seperate database table for custom values and a few other values that dont fit wp_posts)
update_post_meta($post_id, '_keyname', $value);

Custom registration fields in woocommerce not validating

//Add phone number field to customer registration
add_filter( 'register_form', 'custom_phone_no_registration_field' );
function custom_phone_no_registration_field( ) {
echo '<div class="form-row form-row-wide"><label for="reg_phone">'.__('Phone Number', 'woocommerce').' <span class="required">*</span></label>
<input type="text" class="input-text" name="phone" id="reg_phone" size="30" value="'.esc_attr($_POST['phone']).'" /></div>';
}
//Validation registration form after submission using the filter registration_errors
add_action('registration_errors', 'custom_registration_errors_validation', 10,3);
function custom_registration_errors_validation($reg_errors, $sanitized_user_login, $user_email) {
global $woocommerce;
extract($_POST); // extracting $_POST into separate variables
if(empty($phone)) :
$woocommerce->add_error( __( 'Please, fill in all the required fields.', 'woocommerce' ) );
endif;
return $reg_errors;
}
I'm using register_form function to add a phone number field to registration form.it works but the registration_errors function is not working. Can anyone please help me with the code ?
I think you need to validate on the woocommerce_process_registration_errors filter. Take a look at process_registration() method in includes/class-wc-form-handler.php.
add_action( 'woocommerce_process_registration_errors', 'custom_registration_error' );
function custom_registration_errors( $validation_error ){
if ( ! isset( $_POST['phone'] ) ){
$validation_error = new WP_Error( 'phone-error', __( 'Please enter a phone number.', 'your-plugin' ) );
}
return $validation_error;
}

Wordpress's add_action for register_form not working

From what I read in the net, the following code should be adding a "City" field in the user registration form of Wordpress.
Thing is that, it seems to be not working - I don't see the additional "City" field in the user form.
Any help appreciated.
add_action( 'register_form', 'extended_register_form' );
add_filter('registration_errors', 'myplugin_registration_errors', 10, 3);
add_action('user_register', 'myplugin_user_register');
function extended_register_form() {
$city = ( isset( $_POST['city'] ) ) ? $_POST['city']: '';
?>
<p>
<label for="city">City<br />
<input type="text" name="city" id="city" class="input" value="<?php echo esc_attr(stripslashes($city)); ?>" size="25" /></label>
</p>
<?
}
function myplugin_registration_errors ($errors, $sanitized_user_login, $user_email) {
if ( empty( $_POST['city'] ) )
$errors->add( 'city_error', __('<strong>ERROR</strong>: You must include a city.') );
return $errors;
}
function myplugin_user_register ($user_id) {
if ( isset( $_POST['city'] ) )
update_user_meta($user_id, 'city', $_POST['city']);
}
Since Wordpress 3.0.0, the action to call is "signup_extra_fields" instead of "register_form", so you should use:
add_action( 'signup_extra_fields', 'extended_register_form' );
I tried your code and it worked perfectly, perhaps it is because of the <? in line 12... Try <?php instead...
Where have you added the code? As a plugin or in the functions.php of your theme?

Resources