How To Create Multiple Product Variations Woocommerce - woocommerce

I tried to use the function given on this answer: Create programmatically a WooCommerce product variation with new attribute values
But i can't make it work, i inserted it on a my plugin function file instead of functions.php of my theme.
I call that function in this code after a product creation code:
foreach ($variations as $variation) {
$model_name = $variation['name'];
$model_name = explode(',',$model_name);
$color = $model_name[0];
$model = $model_name[1];
$price = $variation['price'];
$stock = $variation['stock'];
// The variation data
$variation_data = array(
'attributes' => array(
'color' => $color,
'model' => $model,
),
'sku' => '',
'regular_price' => $price,
'sale_price' => '',
'stock_qty' => $stock,
);
// The function to be run
create_product_variation( $new_post_id, $variation_data );
}
All the values of product & variations came from a API call from external link. The data is on array format, i can get all those data i need, my problem now is to create the variations of the product and i used this create_product_variation but i cant make it work.
It gives me an error 500 status on my ajax call.

Related

Add attribute value automatically based on user meta key

I have created a registration form (using plugin ultimate-member) for a partner as a salesperson. The key here is:
Label : Registration Number
Meta : 'regno'
Value : X123W
So, each new registrant will get a different value as a salesperson unique ID .
On the other hand, I have created a product which is divided into 3 packages, separated by attribute with values ​​'pa_silver', 'pa_gold', and 'pa_diamond'.
'pa_silver' & 'pa_gold' => self-sold product (no salesperson required)
'pa_diamond' => product entrusted for selling (using salesperson).
Then on products that have taxonomy 'pa_diamond' I've added the attribute:
Label : List
tax : 'pa_list'
value : 'X123W', 'X234W' => this has been created manually.
Targets : What I want is that every time someone registers as a partner, the partner code should be "added" automatically on existing attribute ('pa_list') and on products that have taxonomy 'pa_diamond'.
I'm trying something, like:
$users = get_users( array( 'role' => array( 'partner' ) ) );
foreach($users as $user){
$regno = get_the_author_meta( 'regno', $user->ID);
echo $regno;
}
Note : it output like this => X345WX456W (2 New partner code)
Tried using the code I got from #LoicTheAztec's answer here.
The code is :
$product_id = get_the_ID();
$taxonomy = 'pa_list';
$clean_keywords = array('X345W','X456W');
$term_taxonomy_ids = wp_set_object_terms( $product_id, $clean_keywords, $taxonomy, true );
// Get existing attributes
$product_attributes = get_post_meta( $product_id, '_product_attributes', true);
// get the count of existing attributes to set the "position" in the array
$count = count($product_attributes);
// Insert new attribute in existing array of attributes (if there is any)
$product_attributes[$taxonomy] = array(
'name' => $taxonomy,
'value' => '',
'position' => $count, // added
'is_visible' => '0',
'is_variation' => '0', // added (set the right value)
'is_taxonomy' => '1'
);
// Save the data
update_post_meta( $product_id, '_product_attributes', $product_attributes );
Note : I replaced (manually) $taxonomy -> 'pa_list' and $clean_keywords = array('X345W','X465W');
In attribute field 'pa_list' both partner codes have been added but do not fill or set to product.
I'm having a hard time connecting some logic here.
I hit a dead end to get what I wanted.
Can anyone help me?
Thank You

Get product variation ID from variation SKU [duplicate]

I'm working on a separate templates page, which page gets woocommece product sku using custom field of wordpress post. i need to get product id of that sku for create woocommece object and do further things, here is my code.
global $woocommerce;
//this return sku (custom field on a wordpress post)
$sku=get_field( "product_sku" );
if($sku!=''){
//need to create object, but using sku cannot create a object,
$product = new WC_Product($sku);
echo $product->get_price_html();
}
is there way to get product id before create object, then i can pass the product id to WC_Product class constructor and create object.thank you
WooCommerce 2.3 finally adds support for this in core.
If you are using this version, you can call
wc_get_product_id_by_sku( $sku )
You can use this function (found here). Google is your friend!
function get_product_by_sku( $sku ) {
global $wpdb;
$product_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $sku ) );
if ( $product_id ) return new WC_Product( $product_id );
return null;
}
WooCommerce product is a special post type. Because of this WP_Query might be used to find product by SKU and other parameters. This might be used as an alternative when you need to restrict your search by some other criterias.
For example you might want to specify language if you use Polylang (or other plugins) for site translations. Or you can restrict search by product type.
They do direct SQL query in the WooCommerce method get_product_id_by_sku which I think is perfectly fine in many cases. But might not work if you use translations, it will return random product but not the one in current language.
Example code to find product by SKU using WP_Query (with restriction by product type and language):
public function find( string $lang, string $sku ) {
$query = [
'lang' => $lang,
'post_type' => 'product',
'meta_query' => [
[
'key' => '_sku',
'value' => $sku,
'compare' => '='
]
],
'tax_query' => [
[
'taxonomy' => 'product_type',
'terms' => [ 'grouped' ],
'field' => 'name',
]
]
];
$posts = ( new WP_Query() )->query( $query );
return count( $posts ) > 0 ? $posts[0] : null;
}

Get the value of a field in gravity forms and use that value as a php parameter?

I am trying to dynamically populate two dropdown fields in a Gravity Forms form. The first field dynamically populates with the terms available in a custom post type. I want the second dynamically populated field to contain the list of all post titles within the custom post type AND have those titles filtered by the term selected in the previous dropdown. Is it possible to get the value of a dropdown within Gravity Forms and pass that value as a parameter in $args to use the get_posts($args) function?
I started using the following tutorial as a guide. https://docs.gravityforms.com/dynamically-populating-drop-down-fields/
add_filter( 'gform_pre_render_3', 'populate_procedures' );
add_filter( 'gform_pre_validation_3', 'populate_procedures' );
add_filter( 'gform_pre_submission_filter_3', 'populate_procedures' );
add_filter( 'gform_admin_pre_render_3', 'populate_procedures' );
function populate_procedures( $form ) {
// Procedure Category Dropdown
foreach ( $form['fields'] as &$field ) {
The first field. The following code populates a dropdown field containing a list of all of the terms within a custom post type (procedure):
if ( $field->type != 'select' || strpos( $field->cssClass, 'populate_procedure_categories' ) === false ) {
continue;
}
$terms = get_terms( array(
'taxonomy' => 'procedure_category',
'orderby' => 'name',
'order' => 'ASC',
) );
// you can add additional parameters here to alter the posts that are retrieved
// more info: http://codex.wordpress.org/Template_Tags/get_posts
//$posts = get_posts( 'post_type=procedure&numberposts=-1&post_status=publish' );
$choices = array();
foreach ( $terms as $term ) {
$choices[] = array( 'text' => $term->name, 'value' => $term->name );
}
// update 'Select a Post' to whatever you'd like the instructive option to be
$field->placeholder = 'Select Procedure Category';
$field->choices = $choices;
The second field. The following code dynamically populates the field with all of the the post titles of the custom post type (procedure). I want to filter these results based upon the value selected above.
if ( $field->type != 'select' || strpos( $field->cssClass, 'populate_procedures' ) === false ) {
continue;
}
$args = array(
'post_status' => 'publish',
'post_type' => 'procedure',
'procedure_category' => 'cardiovascular',
);
$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 Procedure';
$field->choices = $choices;
}
return $form;
}
The second dynamically populated field successfully pulls in the filtered list of post titles based on the $args if I explicitly listed the term (in the example above I used 'cardiovascular'). What I am wondering is if there is a way to grab the value of the previous field and use that to filter the results of the second field (without having to reload the page). Any ideas? Does Gravity Forms have a functionality like this built in?
Using this method, you would need to use multiple pages and add the second Drop Down field to the second page on the form. Then, when the user submits the first page, you can access the value of the first Drop Down from the $_POST. Gravity Forms has a helper method for doing this called rgpost(). Here's what your $args might look like:
$args = array(
'post_status' => 'publish',
'post_type' => 'procedure',
'procedure_category' => rgpost( 'input_FIELDID' ),
);
Replace FIELDID with the field ID of your first Drop Down.
With that said, if you want to accomplish this without having to touch any code, try Gravity Forms Populate Anything.
https://gravitywiz.com/documentation/gravity-forms-populate-anything/

Check if a slug is existing, else create a new product in woocommerce

I have here a code below that will insert products into the database in woocommerce :
$post = array(
'post_author' => $user_id,
'post_content' => '',
'post_status' => "publish",
'post_title' => $product->part_num,
'post_parent' => '',
'post_type' => "product",
);
$post_id = wp_insert_post( $post, $wp_error );
But, before inserting a new product, I want to check if a slug is existing in the database, else, I want to add a new one and append a number on the slug.
example input:
$new_url = sanitize_title('This Long Title is what My Post or Page might be');
output :
this-long-title-is-what-my-post-or-page-might-be
Now, I want to check if this slug is already existing in the database. If it is existing, I will append a number on the slug(just like what wordpress permalink is doing). If it is already existing, i want to output this as:
this-long-title-is-what-my-post-or-page-might-be-1
I want to add new product into the database together with this new slug.
Does anybody know?
Not tested but just written that code. Try this and let me know
function slug_exists($slug){
if(get_page_by_path( $slug, OBJECT, 'product' )){
return true;
}
return false;
}
$slug = 'your_slug';
$new_slug = $slug;
$c=1;
while(slug_exists($new_slug)){
$new_slug = $slug.'-'.$c;
$c++;
}
// $new_slug containes your desired slug

NinjaForm - How To Search & Retrieve By DateTime?

I'm using NinjaForm plugin on wordpress. Here how to search and retrieve data:
<?php
$args = array(
'form_id' => $form_id,
'user_id' => $user_id,
'fields' => array(
'34' => 'checked',
'54' => 'Hello World',
),
);
// This will return an array of sub objects.
$subs = Ninja_Forms()->subs()->get( $args );
// This is a basic example of how to interact with the returned objects.
// See other documentation for all the methods and properties of the submission object.
foreach ( $subs as $sub ) {
$form_id = $sub->form_id;
$user_id = $sub->user_id;
// Returns an array of [field_id] => [user_value] pairs
$all_fields = $sub->get_all_fields();
// Echoes out the submitted value for a field
echo $sub->get_field( 34 );
}
What I want to do is searching by DateTime fields. How do I do that?
I have tried change args like this but result same.
$args = array(
'form_id' => 5,
'date_modified'=> '2015-07-25 3:19:09'
);
or like this
$args = array(
'form_id' => 5,
'date_modified'=> '< 2015-07-25 3:19:09'
);
Did I do wrong?
Find Ninja DB Table:
Go into your database using phpmyadmin or something and find the table Ninja Forms is using. Hopefully they're using their own table. If not, you can search each wp table for some of the arg data that you know returns a form from Ninja_Forms(). Or go into the Ninja plugin code and try and find where they interact with the db to find which table they write into.
Write your own mysql search code:
Instead of using Ninja's class to search, use wordpress's built in mysql search and throw in the table you found in step 1.
GLOBAL $wpdb;
$wpdb->get_results($wpdb->prepare("SELECT * FROM `ninja_table` WHERE `date_modified` = %s", $strDate));
I haven't tested, but this would be my course of action.
Use begin_date and end_data parameters to get the submissions
$args = array(
'form_id' => $form_id,
'begin_date' => '2015-07-20 0:00:00',
'end_date' => '2015-07-25 3:19:09'
);
$subs = Ninja_Forms()->subs()->get( $args );

Resources