Dynamically populate two Gravityform select menus - php

I have two select menus built with Gravityforms and I am trying to use the filters below to dynamically populate them with WooCommerce order ids and WooCommerce products. The first foreach loop works as expected. I thought I could the replicate the loop for the second select menu. The queries work as I have tried them in a non-gravityforms form.
I suspect its the variable names I'm using in the second loop?
add_filter('gform_pre_render', 'populate_rma_dropdowns');
add_filter( 'gform_pre_validation', 'populate_rma_dropdowns' );
add_filter( 'gform_admin_pre_render', 'populate_rma_dropdowns' );
add_filter( 'gform_pre_submission_filter', 'populate_rma_dropdowns' );
function populate_rma_dropdowns( $form ) {
if ( $form['title'] != "RMA" ) return $form;
foreach ( $form['fields'] as &$field ) {
if ( $field->type != 'select' || strpos( $field->cssClass, 'order-list' ) === false ) {
continue;
}
$query = new WC_Order_Query( array(
'limit' => -1,
'orderby' => 'date',
'order' => 'DESC',
'return' => 'ids',
) );
$orders = $query->get_orders();
$choices = array(array('text' => 'Please find your order number', 'value' => 0 ));
foreach ( $orders as $order ) {
$choices[] = array( 'text' => $order, 'value' => $order, 'isSelected' => false );
}
$field['choices'] = $choices;
}
foreach ( $form['fields'] as &$field2 ) {
if ( $field2->type != 'select' || strpos( $field2->cssClass, 'product-list' ) === false ) {
continue;
}
$args2 = array( 'post_type' => 'product' ,'posts_per_page' => 100);
$products = get_posts( $args2 );
$choices2 = array(array('text' => 'Please select product', 'value' => 0 ));
foreach ( $products as $product ) {
$choices2[] = array( 'text' => $product->post_title, 'value' => $product->post_title, 'isSelected' => false );
}
$field2['choices2'] = $choices2;
}
return $form;
}

Looks like you've made a small typo in the second loop. You're setting $field2['choices2'] rather than $field2['choices']

I've fixed this: in the second foreach loop I had added a number to the &$field array element
foreach ( $form['fields'] as &$field ) {
...
}
#Marc was correct as well about his suggestion as well. Both drop downs now work as required.

Related

WooCommerce; Query products by attribute term, do not include parent product in query if variation which uses the term is disabled

Scenario:
Variable product has attribute color, term is 'yellow'
Variation with yellow term is disabled
Customer filters product by color 'yellow'
Parent product is displayed even if variation which uses the color 'yellow' is not enabled
Note: Query should contain simple and variation product types.
The query is being called by ajax function, I'm not sure how to use filters if its possible.
The query:
add_action('wp_ajax_getProducts', 'getProducts');
add_action('wp_ajax_nopriv_getProducts', 'getProducts');
function getProducts(){
$input = [
'currentTerm' => $_POST['currentTerm'],
'searchTerms' => $_POST['searchTerms'],
'page' => $_POST['page'],
'color' => $_POST['color'],
'sortBy' => $_POST['sortBy'],
'sortDirection' => $_POST['sortDirection'],
'beltWidth' => $_POST['beltWidth'],
];
// args init
$args = array(
'post_type' => 'product',
'posts_per_page' => 12,
'post_status' => 'publish',
'lang' => pll_current_language()
);
$args['meta_query'] = array(
'relation' => 'AND',
array(
'key' => '_stock_status',
'value' => 'instock'
),
);
$args['tax_query'] = array(
'relation' => 'AND',
);
// 0. Search
if( isset() ) {
$sargs = array(
's' => $input['searchquery'],
);
$args = array_merge($sargs, $args);
}
// 1. Terms
if( isset($input['currentTerm']) ) {
$cat_tax = array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => $input['currentTerm'],
);
array_push($args['tax_query'], $cat_tax);
}
// 2. Page
if( isset($input['page']) ) {
$args['paged'] = $input['page'];
}
// 3. color
if( isset($input['color']) && $input['color'] != 'clear') {
$color_tax = array(
'taxonomy' => 'pa_color',
'field' => 'slug',
'terms' => $input['color'],
'operator' => 'IN'
);
array_push($args['tax_query'], $color_tax);
}
// 4. sort
if ( isset($input['sortBy']) ) {
if ( $input['sortBy'] == 'price' ) {
$args['orderby'] = 'meta_value_num';
$args['meta_key'] = '_price';
} elseif ( $input['sortBy'] == 'name' ) {
$args['orderby'] = 'title';
} else {
$args['orderby'] = 'date';
}
}
if ( isset($input['sortDirection'])) {
if ( $_POST['sortDirection'] == 'asc') {
$args['order'] = 'asc';
} else {
$args['order'] = 'desc';
}
}
// query
$wp_query = new WP_Query( $args );
...
echo json_encode($products);
...
}
The query works fine, and I've found the way to clear results, by filtering the results; but it returns uneven number of products per page, which is not very user friendly.
The solution is to do something like code below within the query arguments, not inside the results loop.
if( isset($input['color']) && $input['color'] != 'clear') {
if ($product['terms']) {
foreach($product['terms'] as $item) {
if ((string) $item['slug'] == $input['color']) {
array_push($products, $product);
}
}
}
}

Relating Wordpress Users with Order Export

We are using Advanced Custom Fields, WP All Export Pro, and WordPress with Woocommerce.
I have an ACF field created for our accountant in users area of WordPress called "traverse_customer_id". This is for her to know what customer this order is for.
I have this ACF field showing in the orders export but the data comes back blank on each export. I think it's because I'm not relating the order with the customer or user ID. I've attempted to use a code snippet from WP All Exports' support without any luck. Could anyone with knowledge help me see what I'm doing wrong?
This is what I have in the "Custom export field" area: (I think this is running the function on each line of the import.)
[sf_helper_meta_query_lookup("traverse_customer_id",{Customer User ID},"user")]
Then I have this below in the Function Editor:
function sf_helper_meta_query_lookup( $meta_key = '', $meta_value = '', $object_type = 'post', $taxonomy = '', $return_field = 'ID', $compare = '=', $custom_args = array() ) {
if ( empty( $object_type ) || empty( $meta_key ) || empty( $meta_value ) ) return;
$func = 'get_posts';
switch ( $object_type ) {
case 'user':
$func = 'get_users';
break;
case 'term':
$func = 'get_terms';
if ( $return_field == 'ID' ) {
$return_field = 'term_id';
}
break;
default:
$func = 'get_posts';
break;
}
if ( ! empty( $custom_args ) ) {
$objects = $func( $custom_args );
if ( ! empty( $objects ) ) {
return $objects[0]->$return_field;
} else {
return false;
}
}
$args = array();
$meta_query = array( array(
'key' => $meta_key,
'value' => $meta_value,
'compare' => $compare
) );
if ( $func == 'get_terms' ) {
$args = array(
'taxonomy' => $taxonomy,
'hide_empty' => false,
'meta_query' => $meta_query
);
} elseif ( $func == 'get_users' ) {
$args = array(
'meta_query' => $meta_query
);
} else {
$args = array(
'post_type' => $object_type,
'meta_query' => $meta_query
);
}
if ( $objects = $func( $args ) ) {
return $objects[0]->$return_field;
} else {
return false;
}
}
Any help would be greatly appreciated!

Pick a random item from an array and pass it to a hidden field in gravity forms

add_filter( 'gform_pre_render_6', 'populate_posts' );
add_filter( 'gform_pre_validation_6', 'populate_posts' );
add_filter( 'gform_pre_submission_6', 'populate_posts' );
add_filter( 'gform_admin_pre_render_6', 'populate_posts' );
function populate_posts( $form ) {
$metavalue = $_POST["input_4"];//store the value of the dropdown.
foreach ( $form['fields'] as &$field ) {
if ( $field->type != 'select' || strpos( $field->cssClass, 'populate-posts' ) === false ) {
continue;
}
$args = array(
'numberposts' => -1,
'post_type' => 'member',
'post_status' => 'publish',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'assets',
'value' => $metavalue,
'compare' => 'LIKE'
))
);
//create array based on selection
$posts = get_posts( $args );
$choices = array();
foreach ( $posts as $post ) {
$choices[] = array( 'text' => $post->post_title, 'value' => $post->post_title );
}
// update 'Select a Post' to whatever you'd like the instructive option to be
$field->placeholder = 'Select a Post';
$field->choices = $choices;
}
return $form;
}
Hi guys,
The purpose of this code is to select from a dropdown which corresponds to a Custom Field, based on the selection, it will then generate a query which based on the metavalue and then put the posts in an array. I was able to store them in an array but I wish to pass a random value from that array to another hidden field in the same form. Is there a more efficient way of doing this particular code?
Thank you so much
You might take a look at Gravity Forms Populate Anything:
https://gravitywiz.com/documentation/gravity-forms-populate-anything/
It will allow you to populate the posts in a Drop Down:
...and then populate data based on the selected item in other fields on the form.

Filters plugin in WP site

I've added in function.php some code to create some filters in my WP site.
The script is the following:
$GLOBALS['my_query_filters'] = array(
'field_1' => 'forma',
'field_2' => 'posa',
'field_3' => 'conduttore',
'field_4' => 'isolante',
'field_5' => 'raggio_minimo_di_curvatura',
'field_6' => 'guaina',
'field_7' => 'marchiatura',
'field_8' => 'tensione_di_esercizio',
'field_9' => 'temp_max_esercizio',
'field_10' => 'temp_min_di_inst',
'field_11' => 'temp_max_corto'
);
// action
add_action('pre_get_posts', 'my_pre_get_posts', 10, 1);
function my_pre_get_posts( $query ) {
// bail early if is in admin
if( is_admin() ) {
return;
}
// get meta query
$meta_query = $query->get('meta_query');
// loop over filters
foreach( $GLOBALS['my_query_filters'] as $key => $name ) {
// continue if not found in url
if( empty($_GET[ $name ]) ) {
continue;
}
// get the value for this filter
// eg: http://www.website.com/events?city=melbourne,sydney
$value = explode(',', $_GET[ $name ]);
// append meta query
$meta_query[] = array(
'key' => $name,
'value' => $value,
'compare' => 'IN',
);
}
// update meta query
$query->set('meta_query', $meta_query);
}
For the moment, this code only shows 10 empty rows but there are any checkbox or filter name.
Can you help me, please?

WooCommerce subcategories(categories of categories) - A tale of php, stupidly limited functions and frustration

The title should give you a pretty good idea about my misadventures. I am working on a project that's made in wordpress and uses WooCommerce, and after a lot of brainstorming and thought about possible compromise, i have reached the point where i am pretty much certain i have to get into the php code to solve the problem conveniently.
The problem is that i have the following website:
As you may have noticed, there is a mash of all the product categories, and what i need to do is split them into 2 main categories: food and drink. I turned what woocommerce can do by its built in functions and i just can't get it to work so i figured i'd have to write my own function. Now if any of you knows that i can actually do it with what i have i'd be happy if somebody told me. If not what i need is to create a function which can actually select all the categories belonging to a parent category or something the likes.
public function product_categories( $atts ) {
global $woocommerce_loop;
extract( shortcode_atts( array (
'number' => null,
'orderby' => 'name',
'order' => 'ASC',
'columns' => '4',
'hide_empty' => 1,
'parent' => ''
), $atts ) );
if ( isset( $atts[ 'ids' ] ) ) {
$ids = explode( ',', $atts[ 'ids' ] );
$ids = array_map( 'trim', $ids );
} else {
$ids = array();
}
$hide_empty = ( $hide_empty == true || $hide_empty == 1 ) ? 1 : 0;
// get terms and workaround WP bug with parents/pad counts
$args = array(
'orderby' => $orderby,
'order' => $order,
'hide_empty' => $hide_empty,
'include' => $ids,
'pad_counts' => true,
'child_of' => $parent
);
$product_categories = get_terms( 'product_cat', $args );
if ( $parent !== "" )
$product_categories = wp_list_filter( $product_categories, array( 'parent' => $parent ) );
if ( $number )
$product_categories = array_slice( $product_categories, 0, $number );
$woocommerce_loop['columns'] = $columns;
ob_start();
// Reset loop/columns globals when starting a new loop
$woocommerce_loop['loop'] = $woocommerce_loop['column'] = '';
if ( $product_categories ) {
woocommerce_product_loop_start();
foreach ( $product_categories as $category ) {
woocommerce_get_template( 'content-product_cat.php', array(
'category' => $category
) );
}
woocommerce_product_loop_end();
}
woocommerce_reset_loop();
return '<div class="woocommerce">' . ob_get_clean() . '</div>';
}
This i identified as the menacing WooCommerce function that does not behave. Help. Please help me :(
What about using WooCommerce's built-in [product_categories] shortcode? You could pass categories you want through the id="" attribute.

Categories