I'm creating a simple plugin that lets me to save some input text fields while the user is registering on the site. This part works well.
But I want to let the users edit this fields on the user account page. I can load the saved info on the database but I can't update this info on the the user metadata.
This code puts the input on the register page, the others 4 possible inputs are dynamically added with jquery if the user clicks on the + button.
add_action ('register_form', 'save_dynamic_inputs', 10);
function save_dynamic_inputs() {
$user_cnpj = ( isset( $_POST['user_cnpj_1'] ) ) ? $_POST['user_cnpj_1'] : '';
$user_cnpj = ( isset( $_POST['user_cnpj_2'] ) ) ? $_POST['user_cnpj_2'] : '';
$user_cnpj = ( isset( $_POST['user_cnpj_3'] ) ) ? $_POST['user_cnpj_3'] : '';
$user_cnpj = ( isset( $_POST['user_cnpj_4'] ) ) ? $_POST['user_cnpj_4'] : '';
?>
<div class="cnpjs"><p><label for="user_cnpj_1"><?php _e( 'CNPJ', 'save_dynamic_inputs' ) ?><br /><input type="text" name="user_cnpj_1" id="user_cnpj_1" class="input" style="width: 445px; value="<?php echo esc_attr( stripslashes( $user_cnpj ) ); ?>" size="19" /><i class="button addmore fa fa-plus" aria-hidden="true"></i></label></p></div>
<?php
}
This another code saves every input if they exist in the user metadata, and this code works, but it's for the register form:
add_action( 'user_register', 'saving_my_dynamic_inputs', 10, 1 );
function saving_my_dynamic_inputs( $user_id ) {
for ($i = 1; $i < 5; $i++) {
if ( isset( $_POST['user_cnpj_'.$i] ) )
update_user_meta($user_id, 'user_cnpj_'.$i, $_POST['user_cnpj_'.$i]);
}
}
And this is the code that I'm using to update the user metadata on the user edit account page, this code does not work.
add_action('woocommerce_created_customer', 'update_fields_profile_user_woo', 10, 1);
function update_fields_profile_user_woo($customer_id) {
if ( isset( $_POST['user_cnpj_1'] ) ) {
update_user_meta($customer_id, 'user_cnpj_1', $_POST['user_cnpj_1']);
} else {
echo "<pre>",print_r($_POST),"</pre>";
exit();
}
}
Where you can read woocommerce_created_customer, I have tried woocommerce_save_account_details and others.
I don't understand why the inputs does not update the user metadata. I have tried to point the form to a php file that gets the $_POST var and prints this, and the array have all the inputs like the sample above:
Like I said, the user account profile loads all the inputs needed, but this last code does not update the info on user metadata.
Woocommerce handles all forms through Form Form Handler Class. You need to create an instance of that class and call its save_account_details method.
Another way to hook it with wp. It will be always invoked at the time of initialization.
function save_wc_additional_details() {
$user_id = get_current_user_id();
if( isset( $_POST['user_cnpj_1'] ) )
update_user_meta( $user_id, 'user_cnpj_1', sanitize_text_field( $_POST['user_cnpj_1'] ) );
if( isset( $_POST['user_cnpj_2'] ) )
update_user_meta( $user_id, 'user_cnpj_2', sanitize_text_field( $_POST['user_cnpj_1'] ) );
if( isset( $_POST['user_cnpj_3'] ) )
update_user_meta( $user_id, 'user_cnpj_3', sanitize_text_field( $_POST['user_cnpj_1'] ) );
if( isset( $_POST['user_cnpj_4'] ) )
update_user_meta( $user_id, 'user_cnpj_4', sanitize_text_field( $_POST['user_cnpj_1'] ) );
}
add_action( 'wp', 'save_wc_additional_details' );
Related
I have a Wordpress site with WooCommerce webshop and a client (hotel) that wants customers to order products in my webshop. I want those customers not to have to fill in the hotel information during checkout (the products are delivered to their room).
I have build a custom page for the hotel where people can place certain products in the cart, and when they want to checkout they press a custom checkout button that prefills the checkout fields. I am using this technique to achieve this: https://newpulselabs.com/prefill-checkout-fields-cartflows/
// Autofill checkout fields from URL
add_filter( 'woocommerce_checkout_fields' , 'prefill_billing_fields' );
function prefill_billing_fields ( $address_fields ) {
// Get the data from the URL
if ( isset( $_GET['fname'] ) || isset( $_GET['lname'] ) || isset( $_GET['email'] ) || isset( $_GET['company'] ) )
{
// wp_die();
$fname = isset( $_GET['fname'] ) ? esc_attr( $_GET['fname'] ) : '';
$lname = isset( $_GET['lname'] ) ? esc_attr( $_GET['lname'] ) : '';
$em = isset( $_GET['email'] ) ? esc_attr( $_GET['email'] ) : '';
$company = isset( $_GET['company'] ) ? esc_attr( $_GET['company'] ) : '';
// First Name
if( isset($_GET['fname']) && ! empty($_GET['fname']) ){
if( isset( $address_fields['billing']['billing_first_name'] ) ){
$address_fields['billing']['billing_first_name']['default'] = $fname;
}
}
// Last Name
if( isset($_GET['lname']) && ! empty($_GET['lname']) ){
if( isset( $address_fields['billing']['billing_last_name'] ) ){
$address_fields['billing']['billing_last_name']['default'] = $lname;
}
}
// Email
if( isset($_GET['email']) && ! empty($_GET['email']) ){
if(isset( $address_fields['billing']['billing_email'] )){
$address_fields['billing']['billing_email']['default'] = $em;
}
}
// Company
if( isset($_GET['company']) && ! empty($_GET['company']) ){
if(isset( $address_fields['billing']['billing_company'] )){
$address_fields['billing']['billing_company']['default'] = $company;
}
}
}
return $address_fields;
}
The url looks like this:
https://www.yourweburl.com/checkout-page/?email=name#example.com&fname=John&lname=Smith&company=ABC Company
And it works perfectly… for new visitors. If a visitor happened to have ordered before in the webshop (and used a different billing address) then that is stored locally in the browser and auto filled.
This technique will not overwrite existing/previous autofill values. I think because it is checking if the cell is empty or not:
if( isset($_GET['fname']) && ! empty($_GET['fname']) ){
if( isset( $address_fields['billing']['billing_first_name'] ) ){
$address_fields['billing']['billing_first_name']['default'] = $fname;
}
}
I tried disabling autofill on the checkout page with this:
add_filter('woocommerce_checkout_get_value','__return_empty_string', 1, 1);
Again that works so well that it removes all prefilled text. So it also removes the information I want to prefill. It works too good ;)
I prefer to alter the first code so that it always overwrites existing values, regardless of what is stored in the browser.
Can anyone help point me in the right direction of how to change the code?
Thanks a lot!
Koen
HI first of thanks and i love this community . I stuck in problem where i want to store the image/item ID in localhost wordpress database instead of image path. I tried everything but failed. Well i am newbie in wordpress so i need a help.
suppose my image/item id is like:---- http://localhost/wpmegameta/wp-admin/upload.php?item=45
databse path:----http://localhost/wpmegameta/wp-content/uploads/2019/05/coding.png
and i want to store only 45 in database
Wordpress database Screenshot
and I want to store only 45 in database like this ---
wp_nonce_field( 'case_study_bg_submit', 'case_study_bg_nonce' );
$lacuna2_stored_meta = get_post_meta( $post->ID ); ?>
<p>
<label for="case-study-bg" class="lacuna2-row-title">Practice Area Icon Image</label>
<img style="max-width:200px;height:auto;" id="meta-image-preview" src="<?php if ( isset ( $lacuna2_stored_meta['meta-image'] ) ){ echo $lacuna2_stored_meta['meta-image'][0]; } ?>" />
<input type="text" name="meta-image" id="meta-image" class="meta_image" value="<?php if ( isset ( $lacuna2_stored_meta['meta-image'] ) ){ echo $lacuna2_stored_meta['meta-image'][0]; } ?>" />
<input type="button" id="meta-image-button" class="button" value="Choose or Upload an Image" />
</p>
<script>
jQuery('#meta-image-button').click(function() {
var send_attachment_bkp = wp.media.editor.send.attachment;
wp.media.editor.send.attachment = function(props, attachment) {
jQuery('#meta-image').val(attachment.url);
jQuery('#meta-image-preview').attr('src',attachment.url);
wp.media.editor.send.attachment = send_attachment_bkp;
}
wp.media.editor.open();
return false;
});
</script>
<?php
}
/**
* Add Case Study background image metabox to the back end of Case Study posts
*/
function lacuna2_add_meta_boxes() {
add_meta_box( 'case-study-bg', 'Game Image', 'lacuna2_case_study_bg', 'post', 'side', 'low' );
}
add_action( 'add_meta_boxes', 'lacuna2_add_meta_boxes' );
/**
* Save background image metabox for Case Study posts
*/
function save_case_study_bg_meta_box($post_id ) {
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
$is_valid_nonce = ( isset( $_POST[ 'case_study_bg_nonce' ] ) && wp_verify_nonce( $_POST[ 'case_study_bg_nonce' ], 'case_study_bg_submit' ) ) ? '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-image' ] ) ) {
update_post_meta( $post_id, 'meta-image', $_POST[ 'meta-image' ] );
}
}
add_action( 'save_post', 'save_case_study_bg_meta_box' );
In wordpress
Image /Item ID==45
Image Path== http://localhost/wpmegameta/wp-content/uploads/2019/05/coding.png
i want to store the image/item ID in wordpress database like=45
i think it's stander to store the image URL ,
but if you want to store just the id do that is to create a table contain all images URL's
and contains tow columns : ID,URL
hope this useful .
I have a custom metabox that I created and have been using on my website for a while, but there's a bit of an issue with how it saves. It tends to be rather volatile, meaning that when backing-up with xml or bulk-editing, it will always lose the data.
The following is the code that I use for the checkbox and to save it
function member_page_featured_meta() {
add_meta_box( 'member_page_meta', __( 'Page Template (if default, select none)', 'member_page_textdomain' ), 'member_page_meta_callback', 'page', 'side', 'low' );
}
add_action( 'add_meta_boxes', 'member_page_featured_meta' );
/**
* Outputs the content of the meta box
*/
function member_page_meta_callback( $post ) {
$values = get_post_meta( $post->ID );
$check = isset( $values['member_box_check'] ) ? esc_attr( $values['member_box_check'][0] ) : '';
wp_nonce_field( basename( __FILE__ ), 'member_page_nonce' );
$member_page_stored_meta = get_post_meta( $post->ID );
?>
<p>
<div class="member_page-row-content">
<label for="featured-checkbox">
<input type="checkbox" name="featured-checkbox" id="featured-checkbox" value="yes" <?php if ( isset ( $member_page_stored_meta['featured-checkbox'] ) ) checked( $member_page_stored_meta['featured-checkbox'][0], 'yes' ); ?> />
<?php _e( 'Member Page', 'member_page_textdomain' )?>
</label><br />
<label for="list-checkbox">
<input type="checkbox" name="list-checkbox" id="list-checkbox" value="yes" <?php if ( isset ( $member_page_stored_meta['list-checkbox'] ) ) checked( $member_page_stored_meta['list-checkbox'][0], 'yes' ); ?> />
<?php _e( 'Home List', 'member_page_textdomain' )?>
</label><br />
</div>
</p>
<?php
}
/**
* Saves the custom meta input
*/
function member_page_meta_save( $post_id ) {
// Checks save status - overcome autosave, etc.
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
$is_valid_nonce = ( isset( $_POST[ 'member_page_nonce' ] ) && wp_verify_nonce( $_POST[ 'member_page_nonce' ], basename( __FILE__ ) ) ) ? 'true' : 'false';
// Exits script depending on save status
if ( $is_autosave || $is_revision || !$is_valid_nonce ) {
return;
}
// Checks for input and saves - save checked as yes and unchecked at no
//This line of code is my hack (just keeps the boxes from saving pretty much)
//if (!empty($_POST['featured-checkbox']) && !empty($_POST['list-checkbox'])) {
if( isset( $_POST[ 'featured-checkbox' ] ) ) {
update_post_meta( $post_id, 'featured-checkbox', 'yes' );
} else {
update_post_meta( $post_id, 'featured-checkbox', 'no' );
};
if( isset( $_POST[ 'list-checkbox' ] ) ) {
update_post_meta( $post_id, 'list-checkbox', 'yes' );
} else {
update_post_meta( $post_id, 'list-checkbox', 'no' );
};
// (bracket ending the first if statement) }
}
add_action( 'save_post', 'member_page_meta_save' );
Is there any way to prevent this issue from happening or is it just something that has to be dealt with when saving check-boxes?
I've sorted out a bit of a hack that is working for now, but whenever I need to make changes to the check-boxes (which is fairly often by the nature of how they're used), I have to comment out a few lines of code, make the change, then un-comment the lines of code and it's a bit unconventional.
I mostly need to make it work when backing-up and restoring (on my backup/production website).
The save_post action is triggered when a post is created or updated, so quick edits and regular edits and the import of posts will trigger it too.
It is actually your script which clears the post meta when doing a quick edit or import, because the POST array does not contain the previously saved values of the checkboxes.
To solve this, you might want to know the "type of saving" currently happening, and only update the post meta when you are on the post edit screen in the admin area. A way of doing this is to check the action parameter of the POST array like the following, because the action parameter only has the value editpost when saving from a post edit screen:
if (filter_input(INPUT_POST, 'action') != 'editpost') {
return;
}
Putting this code at the beginning of the function hooked to the save_post action (member_page_meta_save in your case) will let the rest of the function run only when saving from the post edit screen.
I'm using a plugin on Woocommerce that adds a new metabox with editable quantity number fields onto the admin back-end.
My theme allows for front-end product posting and so I want to add bring some of these fields to the front-end.
I have managed to add the fields in my template file by using :
<?php
$min = get_post_meta( $post->ID, '_wpbo_minimum', true );
$max = get_post_meta( $post->ID, '_wpbo_maximum', true );
?>
<label for="_wpbo_minimum">Minimum Quantity</label>
<input type="number" name="_wpbo_minimum" value="<?php echo $min; ?>" />
<label for="_wpbo_maximum">Maximum Quantity</label>
<input type="number" name="_wpbo_maximum" value="<?php echo $max; ?>" />
Both fields are showing on my front-end product edit form and getting their values from the backend if these were previously filled in.
But now I am struggling with updating and saving the fields with updated values
from front-end or saving new values from front-end if these values were not previously filled in.
I spent hours finding some tutorial on this, I think I should be concentrating on the following code :
update_post_meta($post->ID, '_wpbo_minimum', $_POST['_wpbo_minimum']);
update_post_meta($post->ID, '_wpbo_maximum', $_POST['_wpbo_maximum']);
But I can't figure out if this is correct and where should this code be placed in order to save or update my fields.
I tried placing a function into my functions.php file that looks like this :
/* Update Minimum Qty field */
add_action('save_post', 'save_min_qty');
function save_min_qty($post_id)
{
if(get_post_type($post_id) != "VA_LISTING_PTYPE")
return;
$min = get_post_meta( $post->ID, '_wpbo_minimum', true );
if ( isset( $_POST['_wpbo_minimum'] )) {
$min = $_POST['_wpbo_minimum'];
}
if( isset( $_POST['_wpbo_minimum'] )) {
if ( $min != 0 ) {
$min = wpbo_validate_number( $min );
}
update_post_meta(
$post_id,
'_wpbo_minimum',
strip_tags( $min )
);
}
But this just doesn't seem to be the winner.
Would you be please able to point me to the right direction ?
Below is the code from the actual original plugin that creates metabox in the back-end, I am not sure if it's any relevant to what I need to do in front-end and what part of this and where should I be using it :
<?php
if ( ! class_exists( 'IPQ_Quantity_Meta_Boxes' ) ) :
class IPQ_Quantity_Meta_Boxes {
public function __construct() {
add_action( 'save_post', array( $this, 'save_quantity_meta_data' ) );
}
/* Handle Saving Meta Box Data */
public function save_quantity_meta_data( $post_id ) {
// Validate Post Type
if ( ! isset( $_POST['post_type'] ) or $_POST['post_type'] !== 'product' ) {
return;
}
// Validate User
if ( !current_user_can( 'edit_post', $post_id ) ) {
return;
}
// Verify Nonce
if ( ! isset( $_POST["_wpbo_product_rule_nonce"] ) or ! wp_verify_nonce( $_POST["_wpbo_product_rule_nonce"], plugin_basename( __FILE__ ) ) ) {
return;
}
// Update Rule Meta Values
if ( isset( $_POST['_wpbo_minimum'] )) {
$min = $_POST['_wpbo_minimum'];
}
if( isset( $_POST['_wpbo_minimum'] )) {
if ( $min != 0 ) {
$min = wpbo_validate_number( $min );
}
update_post_meta(
$post_id,
'_wpbo_minimum',
strip_tags( $min )
);
}
/* Make sure Max > Min */
if( isset( $_POST['_wpbo_maximum'] )) {
$max = $_POST['_wpbo_maximum'];
if ( isset( $min ) and $max < $min and $max != 0 ) {
$max = $min;
}
update_post_meta(
$post_id,
'_wpbo_maximum',
strip_tags( wpbo_validate_number( $max ) )
);
}
}
}
endif;
Everything is correct except that you are checking for the wrong post_type - it should be "product" not "VA_LISTING_PTYPE". Your function hooked to save_post is returning early because the post type is not correct.
Incorrect
if(get_post_type($post_id) != "VA_LISTING_PTYPE")
return;
Correct
if (get_post_type($post_id) != "product"){
// bail early if we aren't updating a WooCommerce Product
return;
}
You can see the same check in the plugin you are extending here:
https://github.com/wpbackoffice/woocommerce-incremental-product-quantities/blob/master/includes/class-ipq-product-meta-box.php#L222
I am using the visual composer for the WordPress posts and pages actually for over all. But I want to make some custom meta boxes under the screen of the post editor. Actually already I have made the fields. But now I want to make those fields available in the visual composer. Actually I want to add those fields in the visual editor. How can I do that? Please help me with your valuable knowledge.
Here is my code of the meta boxes
<?php
function myplugin_add_meta_box() {
$screens = array( 'post', 'page' );
foreach ( $screens as $screen ) {
add_meta_box(
'myplugin_sectionid',
__( 'My Post Section Title', 'myplugin_textdomain' ),
'myplugin_meta_box_callback',
$screen
);
}
}
add_action( 'add_meta_boxes', 'myplugin_add_meta_box' );
function myplugin_meta_box_callback( $post ) {
wp_nonce_field( 'myplugin_save_meta_box_data', 'myplugin_meta_box_nonce' );
$value = get_post_meta( $post->ID, '_my_meta_value_key', true );
echo '<label for="myplugin_new_field">';
_e( 'Description for this field', 'myplugin_textdomain' );
echo '</label> ';
echo '<input type="text" id="myplugin_new_field" name="myplugin_new_field" value="' . esc_attr( $value ) . '" size="25" />';
}
function myplugin_save_meta_box_data( $post_id ) {
if ( ! isset( $_POST['myplugin_meta_box_nonce'] ) ) {
return;
}
// Verify that the nonce is valid.
if ( ! wp_verify_nonce( $_POST['myplugin_meta_box_nonce'], 'myplugin_save_meta_box_data' ) ) {
return;
}
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
// Check the user's permissions.
if ( isset( $_POST['post_type'] ) && 'page' == $_POST['post_type'] ) {
if ( ! current_user_can( 'edit_page', $post_id ) ) {
return;
}
} else {
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
}
/* OK, it's safe for us to save the data now. */
// Make sure that it is set.
if ( ! isset( $_POST['myplugin_new_field'] ) ) {
return;
}
// Sanitize user input.
$my_data = sanitize_text_field( $_POST['myplugin_new_field'] );
// Update the meta field in the database.
update_post_meta( $post_id, '_my_meta_value_key', $my_data );
}
add_action( 'save_post', 'myplugin_save_meta_box_data' );
I see that you are echoing your fields as inputs. You need to use the wp_editor() function instead. It will take care of the wysiwyg (visual editor) field creation for you.