Gravity Forms - Accessing field defined in shortcode - wordpress

I'm writing a rating system using Gravity Forms. Next to each post is a "Vote" link which opens a lightbox with a Gravity Forms shortcode in it. The shortcode populates two hidden fields - the Post ID and the User ID:
[gravityform id="2" field_values="gf_rating_post=123&gf_rating_user=456" title="false" description="false" ajax="true" tabindex="49"]
Inside the form are dropdown menus to rate the various elements, from 1-10. I'm trying to write code to insert SELECTED with the previously selected value from the dropdown, but I need to be able to reference the Post ID in order to retrieve that previously selected value.
add_filter('gform_pre_render_2', 'ac_populate_post_ratings');
add_filter('gform_pre_validation_2', 'ac_populate_post_ratings');
add_filter('gform_pre_submission_filter_2', 'ac_populate_post_ratings');
add_filter('gform_admin_pre_render_2', 'ac_populate_post_ratings');
function ac_populate_post_ratings($form) {
foreach ( $form['fields'] as &$field ) {
if ( $field->type != "select" || strpos( $field->cssClass, 'populate-posts' ) ) {
continue;
}
$choices = $field->choices;
foreach ( $choices as $choice ) {
// echo "defaultValue: " . $field->defaultValue . "<br />";
$newchoices[] = array( 'text' => $choice['text'], 'value' => $choice['value'] );
}
$field->choices = $newchoices;
}
return $form;
}
It seems that because the Post ID value is dynamically added to the form, it isn't able to be referenced using the field's defaultValue, which is always empty even though when you view the source, the input value is set correctly.
Any ideas how I can reference that Post ID inside the ac_populate_post_ratings() function?

As a last ditch effect, I contacted Gravity Forms support, and they came through with the goods.
The field defaultValue property will only contain a value if you have configured that setting in the form editor. Values which are being dynamically populated are not available from the $form.
The gform_pre_render filter is passed the dynamic population values from the shortcode in its third param.
I needed to change this line:
add_filter('gform_pre_render_2', 'ac_populate_post_ratings');`
to this:
add_filter('gform_pre_render_2', 'ac_populate_post_ratings', 10, 3 );`
And this line:
function ac_populate_post_ratings($form) {
to this:
function ac_populate_post_ratings( $form, $ajax = false, $field_values = array() ) {
And now I can access the values like so:
$gf_rating_post = rgar( $field_values, 'gf_rating_post' );

Related

Woocommerce - Remove fields from woocommerce_form_field including validation

I am trying to customise the Woocommerce myaccount page, in particular the edit address page.
I want to display both the shipping + billing address forms on a single page. Ideally, in a single form with a one save button. I also need to remove a lot of the fields, so that it's a much simpler form of just an address (no name, company, etc).
I have implemented the code found on This Answer. It works nicely in that it shows both forms. However, I cannot remove the fields from the forms. If I try code like this:
add_filter( 'woocommerce_billing_fields' , 'custom_override_billing_fields' );
add_filter( 'woocommerce_shipping_fields' , 'custom_override_shipping_fields' );
function custom_override_billing_fields( $fields ) {
unset($fields['billing_country']);
unset($fields['billing_company']);
unset($fields['billing_first_name']);
unset($fields['billing_last_name']);
unset($fields['billing_phone']);
unset($fields['billing_email']);
return $fields;
}
function custom_override_shipping_fields( $fields ) {
unset($fields['shipping_country']);
unset($fields['shipping_company']);
unset($fields['shipping_first_name']);
unset($fields['shipping_last_name']);
return $fields;
}
It doesn't work, the fields are no longer shown but the form does not save on click... it just redirects to /my-account/edit-address/billing/ - and doesn't save. (the same form shown on this page doesn't save either).
I've also tried:
foreach ( $billing_fields as $key => $field ) :
if($key != 'billing_first_name' && $key != 'billing_last_name') :
woocommerce_form_field( $key, $field, $userMeta[$key][0] );
endif;
endforeach;
This removes the field from displaying, BUT the validation still exists - and any filter code I add to functions using
woocommerce_checkout_fields to remove the validation doesn't seem to affect this form at all.
Is there a way to either:
Remove fields from this form generated by woocommerce_form_field including the validation?
Create a custom form that allows me to set the input fields manually in the code, and update any fields that are there, ignoring the validation from Woocommerce completely?
This should work 100%. You need to state whether the fields you are removing is from billing or shipping and this is done by adding the ['billing'] or ['shipping'], whichever it is.
After this, adding the function directly to woocommerce_checkout_fields will apply both for billing and shipping.
For phone and company fields you can disable it in admin panel itself, do it.
Edit: And yes, all validation that was involved with the fields in the past will be removed. You can then apply any validation you need.
add_filter( 'woocommerce_checkout_fields' , 'brandimagemarketer_remove_billing_fields_checkout' );
function brandimagemarketer_remove_billing_fields_checkout( $fields ) {
unset($fields['billing']['billing_country']);
unset($fields['billing']['billing_first_name']);
unset($fields['billing']['billing_last_name']);
unset($fields['billing']['billing_email']);
unset($fields['shipping']['shipping_country']);
unset($fields['shipping']['shipping_first_name']);
unset($fields['shipping']['shipping_last_name']);
unset($fields['shipping']['shipping_email']);
return $fields;
}

Advanced Custom Fields Default Values Based On Current User

How to set product field value based on current user's display name in ACF plugin?
Following acf/load_field[acf/load_field filter documentation][1] I tried adding this to my functions.php:
function acf_load_user_display_name( $field ){ $user = wp_get_current_user(); $display_name = $user->display_name; return $user->display_name; } // acf/load_field - default for product_display_name field add_filter('acf/load_field/name=product_display_name', 'acf_load_user_display_name');
This code makes a bug on the edit-product page and ACF-edit-field groups, and the custom field "product_display_name" is still blank on the product page.
[1]: https://www.advancedcustomfields.com/resources/acf-load_field/

WordPress Shortcode with fallback

I'm building a simple plugin that uses the geoservices web service and what I'm trying to do is dynamically change the content on a WordPress page based on their location. I have it working somewhat but my issue is that it's returning both the location-specific text AND the default. I know it's because i'm using the shortcode instance more than once but I don't know how to change it to ONLY show the location specific content and if the location is not set or does not match the shortcode params then fall back to the default one. I don't want to add "default" as a shortcode param because it could contain HTML or something else.
Here is an example of my shortcode:
[geo city="Orlando"]555-123-6349[/geo][geo city="Raleigh"]919-999-9999[/geo][geo city="Default"]Default text here[/geo]
So based on the above, the desired result would show Orlando's phone number if the user is from Orlando or it would show Raleigh number if they are from Raleigh. Otherwise, if they are not from either of those places, it would use the default.
Here is my shortcode:
function geo_services( $atts , $content = null ) {
// Attributes
extract(shortcode_atts(array(
'city' => '',
'state' => '',
), $atts));
require_once('geoplugin.class.php');
$geoplugin = new geoPlugin();
$geoplugin->locate();
if($city === $geoplugin->city){
return $content;
} elseif ($state === $geoplugin->region){
return $content;
} elseif ($city === 'Default') {
return $content;
}
}
add_shortcode( 'geo', 'geo_services' );
And here is what is happening when I use the example shortcode above:
I believe you may be misunderstanding how shortcodes work in WP. In your example, you have added 3 shortcodes to the content. Each of those shortcodes is going to run. Not one or the other. So doing,
[geo city="Orlando"]555-123-6349[/geo][geo city="Raleigh"]919-999-9999[/geo][geo city="Default"]Default text here[/geo]
means that each of those will be called and evaluated. $geoplugin->city is always going to return the city of the user, regardless of what attributes you supplied. And since you are returning $content in all cases, it will always spit out the content that you added inside the shortcode. This is why you are seeing all 3 responses.
Instead, I would try the approach below. If your goal is to spit out content based on the city of the user, you really don't need to supply an attribute to the shortcode. See the following example:
//in your post/page content, simply use the shortcode geo
[geo]
//your function should be
function geo_services( $atts , $content = null ) {
//
require_once('geoplugin.class.php');
//
$geoplugin = new geoPlugin();
$geoplugin->locate();
//
switch( $geoplugin->city ) {
case 'Orlando':
return '555-123-6349';
break;
case 'Raleigh':
return '919-999-9999';
break;
default:
return 'Default text here';
break;
}
}
add_shortcode( 'geo', 'geo_services' );
Providing another answer based on OP comments. If you really need to manage the content via the WYSIWYG, then you could supply the content for each city as an attribute.
//add shortcode to post/page content
[geo orlando="555-123-6349" raleigh="919-999-9999" default="Custom default text here"]
//your function should be
function geo_services( $atts , $content = null ) {
//don't use extract since we expect X number of atts now
$atts = shortcode_atts(array(
'default' => 'Default text here'
), $atts);
//
require_once('geoplugin.class.php');
//
$geoplugin = new geoPlugin();
$geoplugin->locate();
//was the city provided as an attribute?
if( isset($atts[ strtolower($geoplugin->city) ]) ) {
return $atts[ strtolower($geoplugin->city) ];
}else {
return $atts['default'];
}
}
add_shortcode( 'geo', 'geo_services' );
You may have to get creative with the HTML portion of the content, but now you can include X number of cities, with their custom content, in the shortcode itself. If the city is not supplied, or does not match, it will fallback to the default.

Show Advanced custom field in wpallexport

I wanted to export a Advanced custom field and therefore I used the Function Editor in wpallexport, but nothing is showing up.
I created a ACF field for the product in woocommerce (wirtschaftlicher_eigentumer), I tried to get it over the product_id but nothing appears.
function wirtschaftlicher_eigen ($product_id) {
if ( ! empty($product_id) ) {
return get_field('wirtschaftlicher_eigentumer', 'product_' . $product_id);
}
}
Want to get the field but instead it's empty.
You need to change
return get_field('wirtschaftlicher_eigentumer', 'product_' . $product_id);
To
return get_field('wirtschaftlicher_eigentumer', $product_id);
The $product_id will return the current post id.

How to update cart item meta - woocommerce

I know we can add meta for woocommerce cart item using woocommerce_add_cart_item_data hook.
Is there any way to update existing cart item meta.?
Yes, but it seems, only via accessing the cart directly:
global $woocommerce;
$woocommerce->cart->cart_contents[$cart_item_key]['whatever_meta'] = 'testing';
$woocommerce->cart->set_session(); // when in ajax calls, saves it.
I would recommend to remove and re-add the product, as other meta data could be lost (as in Phong Tran's answer).
Based on #DanielSalcedos answer, only keeping the absolute minimum required to answer the question.
I know It's been a while, but as it's still not answered, and it took me lots of sweat and a pint of blood, I share my solution here.
First
I'll assume you know how to add metadata to a cart and into an order. If not, you can have a look at pwnewbie's solution but I recommend you the full article at Wisdm labs
Wisdm's method takes many steps. First you create a PHP's session variable trough Ajax. Second, you intercept woocommerce_add_cart_item_data filter to add your Session variable to woocommerce session.
The thing about woocommerce_add_cart_item_data filter is that it gets executed in the middle of the add to cart process, so, if you add your variable to the main $wooocmmerce object, at some point, it get's stored as the add-to-cart event. (Sort of)
The idea
What if I want to edit that metadata and not any of the standard cart properties. The ideal would be to get a filter or an action that runs in the middle of saving something. The problem is that as long as we don't change anything else, there's no hook to run (I tried with woocommerce_update_cart_action_cart_updated hook that runs after coupons, quantities and removals from cart had happened, but it never fired as I never passed the validations)
My approach
In a shell, rebuild as little as possible, as much as needed. I added a synchronous ajax event to the cart form OnSubmit event. (I want my UI to be updated with my changes, so the reload must happen after my update)
AJAX:
var myFlag33322805 = true;
$('form').submit(function(e){
if(myFlag33322805){
myFlag33322805 = false;
e.preventDefault(); // Flag and prevent default to syncronize submits
var kart = []; // Will retrieve every cart item's meta
$('.cartRow').each(function(){
//This object will store your meta data and be pushed into kart array
var kitm = {
'p' : $(this).data('product_id'),
'm' : $(this).find('select[name=myMetaData]').val(),
'k' : $(this).data('key')
};
kart.push(kitm);
});
var data = {
'action': 'Ajax_Update_My_MetaData_33322805',
'k': kart
};
$.post(VKVAjax.ajaxurl, data, function (response) {
// Might do something with the response here
});
$('form').submit(); // This time, the form will submit, but AJAX wont run because of myFlag33322805 = false
}
});
The magic:
The php ajax response is a function that will receive my meta data to update (actually, all of it, updated or not), and will take the global $woocommerceobject to insert the meta data AND save it to the session:
PHP:
function fn_Update_My_MetaData_33322805(){
global $woocommerce;
$cart = $woocommerce->cart->cart_contents;
$updt = Array();
foreach ($_POST['k'] AS $item){
$product = new stdClass();
$updtCL = new stdClass();
$product->{'id'} = $item['p']; //This is product id
$product->{'mymeta'} = $item['m']; //This is metadata
$updtCL->{'krtkey'} = $item['k']; //This is product key in cart
$updtCL->{'meta'} = $product;
$updt[] = $updtCL;
}
// cycle the cart replace the meta of the correspondant key
foreach ($cart as $key => $item) {
foreach($updt as $updtitem){
if($key == $updtitem->krtkey){ // if this kart item corresponds with the received, the meta data is updated
// Update the content of the kart
$woocommerce->cart->cart_contents[$key]['vkv_AlternCart_value'] = $updtitem->meta;
}
}
}
// This is the magic: With this function, the modified object gets saved.
$woocommerce->cart->set_session();
wp_die('{"e":"ok", "Updt": "'.count($arrupdt).'"}');
}
Of course, this should be hooked as any other ajax event.
add_action('wp_ajax_nopriv_Ajax_Update_My_MetaData_33322805', 'fn_Ajax_Update_My_MetaData_33322805');
add_action('wp_ajax_Ajax_Update_My_MetaData_33322805', 'fn_Ajax_Update_My_MetaData_33322805');
Conclussion
You can update the meta data of a cart item with a synchronous Ajax call, overwritting the object directly to the $woocommerce global variable and saving it with the $woocommerce->cart->set_session(); method.
Footnotes
It's not the ideal method, and is quite risky to work directlly with the $woocommerce global. I would love to know of a better approach.
I'm newbie and my English is not good so the answer may be a little confusing.
Thank vlad274 for the advice.
My approach:
Same with Daniel Salcedo, I also try to change the metadata by editing woocommerce_sessions, but there is a problem. When adding an item to the cart, the woocommerce will create a unique cart_item_key for it by md5 (product_id + ... + metadata), then look for this cart_item_key already exists, if available, this item will be updated in quantity, otherwise will create a new item.
This means that if you change the meta value of the hat product from blue to red, then add the hat product with blue, instead of creating a new item blue hat, it will only increase the quantity of red hat, you need to change the cart_item_key if you want the cart to be updated correctly.
Changing cart_item_key is quite risky, instead we can simply remove and re-add the product. Like this
// get cart_item_key of item you want to change
$cart_item_key_old = $_POST['cart_item_key'];
// retrieve its information
$cart_item_old = WC()->cart->cart_contents[ $cart_item_key_old ];
$product_id_old = $cart_item_old['product_id'];
$quantity_old = $cart_item_old['quantity'];
$variation_id_old = $cart_item_old['variation_id'];
$variation_old = $cart_item_old['variation'];
// creating a cart_item_key with the same information except metadata
$cart_item_key_new = WC()->cart->generate_cart_id( $product_id_old, $variation_id_old, $variation_old, ['color'=>'red'] );
// check new cart_item_key already exists
$found = WC()->cart->find_product_in_cart( $cart_item_key_new );
// if true, update its quantity
if ($found != '') {
$new_quantity = $cart_item_old['quantity'] + WC()->cart->cart_contents[ $cart_item_key_new ]['quantity'];
WC()->cart->set_quantity( $cart_item_key_new, $new_quantity );
}
// else, re-add with new metadata
else {
WC()->cart->add_to_cart($product_id_old, $quantity_old, $variation_id_old, $variation_old, ['color'=>'red'] );
}
// finally delete the old item
WC()->cart->remove_cart_item($cart_item_key_old);
wp_die();
Note: If you want to submit cart form instead of page refreshes after running the above ajax, the quantity of item is likely to be overridden by the set_quantity method when woocommerce update_cart. In this case you just need to return new_quantity and change the input value by js before submitting the form.
Full code:
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
...
?>
<!-- place it anywhere within the foreach -->
<div class="box-type-field">
<select class="box-type" name="box-type" cart_item_key="<?php echo $cart_item_key ?>">
<option <?php echo $cart_item['box-type']=='boxes'?"selected":""; ?> value="boxes"><?php _e( 'Boxes', 'woocommerce' ); ?></option>
<option <?php echo $cart_item['box-type']=='bags'?"selected":""; ?> value="bags"><?php _e( 'Bags', 'woocommerce' ); ?></option>
</select>
</div>
<?php
...
}
AJAX:
$('.box-type-field .box-type').live('change', function () {
var cartItemKey = $(this).attr("cart_item_key");
var boxType = $(this).val();
$.ajax({
type : "post",
url : '<?php echo admin_url('admin-ajax.php');?>',
datatype: 'json',
data : {
action : "update_cart_boxtype",
cart_item_key : cartItemKey,
box_type : boxType,
},
success: function(cartItem) {
cartItemKey = cartItem[0];
cartItemQty = cartItem[1];
if (cartItem) $('input[name="cart['+cartItemKey+'][qty]"]').val(cartItemQty); // update quantity
$('.woocommerce-cart-form button[type="submit"]').click(); // submit form
}
})
})
PHP:
add_action( 'wp_ajax_update_cart_boxtype', 'update_cart_boxtype_init' );
add_action( 'wp_ajax_nopriv_update_cart_boxtype', 'update_cart_boxtype_init' );
function update_cart_boxtype_init() {
if ( ! WC()->cart->is_empty() ) {
$cart_item_key = (isset($_POST['cart_item_key']))?$_POST['cart_item_key'] : '';
$cart_item = WC()->cart->cart_contents[ $cart_item_key ];
$box_type = (isset($_POST['box_type']))?$_POST['box_type'] : '';
$cart_updated = false;
$cart_item_key_new = WC()->cart->generate_cart_id( $cart_item['product_id'], $cart_item['variation_id'], $cart_item['variation'], ['box-type'=>$box_type] );
$found = WC()->cart->find_product_in_cart( $cart_item_key_new );
if ($found != '') {
$new_qty = $cart_item['quantity'] + WC()->cart->cart_contents[ $cart_item_key_new ]['quantity'];
WC()->cart->remove_cart_item($cart_item_key);
wp_send_json_success([$cart_item_key_new, $new_qty]);
} else {
WC()->cart->add_to_cart($cart_item['product_id'], $cart_item['quantity'], $cart_item['variation_id'], $cart_item['variation'], ['box-type' => $box_type]);
$cart_updated = true;
WC()->cart->remove_cart_item($cart_item_key);
wp_send_json_success(false);
}
}
wp_die();
}
Step 1: Add Data in a Custom Session, on ‘Add to Cart’ Button Click
For those of you who have worked with WooCommerce might know that on the click of the ‘Add to Cart’ button the product page gets refreshed and the user data is lost. Hence, we should add the custom data from our product page to a custom session created using Ajax. This code is invoked before the WooCommerce session is created.
<?php
add_action('wp_ajax_wdm_add_user_custom_data_options', 'wdm_add_user_custom_data_options_callback');
add_action('wp_ajax_nopriv_wdm_add_user_custom_data_options', 'wdm_add_user_custom_data_options_callback');
function wdm_add_user_custom_data_options_callback()
{
//Custom data - Sent Via AJAX post method
$product_id = $_POST['id']; //This is product ID
$user_custom_data_values = $_POST['user_data']; //This is User custom value sent via AJAX
session_start();
$_SESSION['wdm_user_custom_data'] = $user_custom_data_values;
die();
}
Step 2: Add Custom Data in WooCommerce Session
At this step, the WooCommerce session has been created and is now available for us to add our custom data. We use the following code to add the custom data from the session we have created into the WooCommerce session. At this step, our session is also unset since the data in it has been captured and it is not needed anymore.
add_filter('woocommerce_add_cart_item_data','wdm_add_item_data',1,2);
if(!function_exists('wdm_add_item_data'))
{
function wdm_add_item_data($cart_item_data,$product_id)
{
/*Here, We are adding item in WooCommerce session with, wdm_user_custom_data_value name*/
global $woocommerce;
session_start();
if (isset($_SESSION['wdm_user_custom_data'])) {
$option = $_SESSION['wdm_user_custom_data'];
$new_value = array('wdm_user_custom_data_value' => $option);
}
if(empty($option))
return $cart_item_data;
else
{
if(empty($cart_item_data))
return $new_value;
else
return array_merge($cart_item_data,$new_value);
}
unset($_SESSION['wdm_user_custom_data']);
//Unset our custom session variable, as it is no longer needed.
}
}
Step 3: Extract Custom Data from WooCommerce Session and Insert it into Cart Object
At this stage, we have default product details along with the custom data in the WooCommerce session. The default data gets added to the cart object owing to the functionality provided by the plugin. However, we need to explicitly extract the custom data from the WooCommerce session and insert it into the cart object. This can be implemented with the following code.
add_filter('woocommerce_get_cart_item_from_session', 'wdm_get_cart_items_from_session', 1, 3 );
if(!function_exists('wdm_get_cart_items_from_session'))
{
function wdm_get_cart_items_from_session($item,$values,$key)
{
if (array_key_exists( 'wdm_user_custom_data_value', $values ) )
{
$item['wdm_user_custom_data_value'] = $values['wdm_user_custom_data_value'];
}
return $item;
}
}
Step 4: Display User Custom Data on Cart and Checkout page
Now that we have our custom data in the cart object all we need to do now is to display this data in the Cart and the Checkout page. This is how your cart page should look after the custom data has been added from the WooCommerce session to your Cart.
My-Cart-Page

Resources