Import multiple attributes with variations to woocommerce variable products - wordpress

I am working with a script to import multiple attributes to a variable products.
I am getting attributes in the following format.
the code script is as follow
function products_options_values($a) {
$result = array(array());
foreach ($a as $k => $list) {
$_tmp = array();
foreach ($result as $result_item) {
foreach ($list as $list_item) {
$_tmp[] = array_merge($result_item, array($k => $list_item));
}
}
$result = $_tmp;
}
return $result;
} if($attributes = get_result("select * from products_attributes where products_id = X ")){
wp_set_object_terms($product_id, 'variable', 'product_type');
$attrib_array = array();
$attrib_combo = array();
$max_price = $product['products_price'];
$min_price = $product['products_price'];
foreach ($attributes as $attribute) {
$slug = sanitize_title($attribute['products_options_name']);
$attrib_array[$slug] = array(
'name' => $attribute['products_options_name'],
'value' => ltrim($attrib_array[$slug]['value'] . ' | ' . $attribute['products_options_values_name'], ' | '),
'position' => 0,
'is_visible' => 1,
'is_variation' => 1,
'is_taxonomy' => 0);
if($attribute['price_prefix'] == '-')$attributeprefix = '-';
else if($attribute['price_prefix'] == '+')$attributeprefix = '+';
else $attributeprefix = '';
$attrib_combo[$slug][] = array($attribute['products_options_values_name'], $attributeprefix . $attribute['options_values_price']);
}
$combos = products_options_values($attrib_combo);
foreach ($combos as $combo) {
$variation_id = wp_insert_post(array(
'post_title' => 'Product ' . $product_id . ' Variation',
'post_content' => '',
'post_status' => 'publish',
'post_type' => 'product_variation',
'post_author' => 1,
'post_parent' => $product_id
));
$opt_price = $product['products_price'] .$attributeprefix. $attribute['options_values_price'];
$special_price = $special['specials_new_products_price'];
foreach ($combo as $k => $v) {
update_post_meta($variation_id, 'attribute_' . $k, $v[0]);
$opt_price += $v[1];
$special_price += $v[1];
}
update_post_meta($variation_id, '_regular_price', $opt_price);
update_post_meta($variation_id, '_price', $opt_price);
update_post_meta($variation_id, '_thumbnail_id', 0);
update_post_meta($variation_id, '_stock', $product['products_quantity']);
if ($opt_price > $max_price) {
$max_price = $opt_price;
}
if ($opt_price < $min_price) {
$min_price = $opt_price;
}
}
update_post_meta($product_id, '_product_attributes', $attrib_array);
update_post_meta($product_id, '_max_variation_regular_price', $max_price);
update_post_meta($product_id, '_min_variation_regular_price', $min_price);
update_post_meta($product_id, '_max_variation_price', $max_price);
update_post_meta($product_id, '_min_variation_price', $min_price);}
with this code i can create attributes and variations successfully
but when i see in the website and select a variable product and click add to cart button error display
Invalid value posted for
I am not understanding where I have error or missing some meta field to cover.
help me seniors if i am missing some meta fields or somethin code issues.

Just for giggles and kicks - in your config file - is your live site set to your home URL, or is it blank? you should make sure it will be empty. I have had some really weird things happen with SEF when that is not configured properly.
You also have a lot of script going on - especially on that front page. If the site is working without the SEF installed, and broken when it is turned on - more than likely a confict.
Just a side note - Joomla's core SEF works just fine. Don't bother with third party stuff - you really do not need it.

Related

How to programmatically set the product attribute variation price in woocommerce?

I have a product attribute variation which has options of -
small - $20
medium - $25
large - $30
Since all the products in the store has the same price for this variations.
How to set the price for the attribute values programmatically?
3 attribute variation buttons are show on product page when I add them as variations.
How to change the price of product when "small" option is selected programmatically instead of setting price in variation options in admin panel.
As Per our understanding to want to add products with different sizes and different prices.
There is 2 way:
1. You can add from woocommerece dashboard like this:
https://www.ostraining.com/blog/woocommerce/product-variations/
You can add programmatically like this:
function insert_product ($product_data)
{
$post = array( // Set up the basic post data to insert for our product
'post_author' => 1,
'post_content' => $product_data['description'],
'post_status' => 'publish',
'post_title' => $product_data['name'],
'post_parent' => '',
'post_type' => 'product'
);
$post_id = wp_insert_post($post); // Insert the post returning the new post id
if (!$post_id) // If there is no post id something has gone wrong so don't proceed
{
return false;
}
update_post_meta($post_id, '_sku', $product_data['sku']); // Set its SKU
update_post_meta( $post_id,'_visibility','visible'); // Set the product to visible, if not it won't show on the front end
wp_set_object_terms($post_id, $product_data['categories'], 'product_cat'); // Set up its categories
wp_set_object_terms($post_id, 'variable', 'product_type'); // Set it to a variable product type
insert_product_attributes($post_id, $product_data['available_attributes'], $product_data['variations']); // Add attributes passing the new post id, attributes & variations
insert_product_variations($post_id, $product_data['variations']); // Insert variations passing the new post id & variations
}
function insert_product_attributes ($post_id, $available_attributes, $variations)
{
foreach ($available_attributes as $attribute) // Go through each attribute
{
$values = array(); // Set up an array to store the current attributes values.
foreach ($variations as $variation) // Loop each variation in the file
{
$attribute_keys = array_keys($variation['attributes']); // Get the keys for the current variations attributes
foreach ($attribute_keys as $key) // Loop through each key
{
if ($key === $attribute) // If this attributes key is the top level attribute add the value to the $values array
{
$values[] = $variation['attributes'][$key];
}
}
}
$values = array_unique($values); // Filter out duplicate values
wp_set_object_terms($post_id, $values, 'pa_' . $attribute);
}
$product_attributes_data = array(); // Setup array to hold our product attributes data
foreach ($available_attributes as $attribute) // Loop round each attribute
{
$product_attributes_data['pa_'.$attribute] = array( // Set this attributes array to a key to using the prefix 'pa'
'name' => 'pa_'.$attribute,
'value' => '',
'is_visible' => '1',
'is_variation' => '1',
'is_taxonomy' => '1'
);
}
update_post_meta($post_id, '_product_attributes', $product_attributes_data); // Attach the above array to the new posts meta data key '_product_attributes'
}
function insert_product_variations ($post_id, $variations)
{
foreach ($variations as $index => $variation)
{
$variation_post = array( // Setup the post data for the variation
'post_title' => 'Variation #'.$index.' of '.count($variations).' for product#'. $post_id,
'post_name' => 'product-'.$post_id.'-variation-'.$index,
'post_status' => 'publish',
'post_parent' => $post_id,
'post_type' => 'product_variation',
'guid' => home_url() . '/?product_variation=product-' . $post_id . '-variation-' . $index
);
$variation_post_id = wp_insert_post($variation_post); // Insert the variation
foreach ($variation['attributes'] as $attribute => $value) // Loop through the variations attributes
{
$attribute_term = get_term_by('name', $value, 'pa_'.$attribute); // We need to insert the slug not the name into the variation post meta
update_post_meta($variation_post_id, 'attribute_pa_'.$attribute, $attribute_term->slug);
}
update_post_meta($variation_post_id, '_price', $variation['price']);
update_post_meta($variation_post_id, '_regular_price', $variation['price']);
}
}
function insert_products ($products)
{
if (!empty($products)) // No point proceeding if there are no products
{
array_map('insert_product', $products); // Run 'insert_product' function from above for each product
}
}
$json = file_get_contents('product-data.json'); // Get json from sample file
// $products_data = json_decode($json_file, true); // Decode it into an array
echo json_last_error();
// if(get_magic_quotes_gpc()){
// $d = stripslashes($json);
// }else{
// $d = $json;
// }
$d = json_decode($d,true);
$products_data = json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $json), true );
echo "<h1>json</h1>";
echo "<pre>";
print_r($json);
echo "</pre>";
echo "<h1>Product data</h1>";
echo "<pre>";
var_dump($products_data);
echo "</pre>";
insert_products($products_data);
Where $product_data sample:
$product_data = array(
'sku' => '123SKU',
'categories' => array('size', 'color'),
'available_attributes' => array('size', 'color'),
'variations' => array(
'size' => array(
'attributes' => array( 'XL', 'M', 'S' ),
),
'color' => array(
'attributes' => array( 'Blue', 'Red', 'Green' )
)
)
)
insert_products($products_data);
Note: You can create product-data.json and import product or you can create $product_data = (); and set on insert_products() function.
For Aditional Info:
You can also check this URL for more info https://newbedev.com/create-programmatically-a-woocommerce-product-variation-with-new-attribute-values

WordPress listing all/selected pages in A-Z index

I want to list all pages as well as selected pages in A-Z listing in WordPress. I know there are a number of plugins available, but I want this without a plugin.
Update
sorry if question is not clear, i want A-Z listing like attached image
i have solved this issue,
just need to put if condition, here is the code
$arr[0] = array(2=>2983);
$arr[1] = array(2=>2981);
$arr[2] = array('A'=>20);
$arr[3] = array('A'=>25);
print "<pre>";
print_r($arr);
$newArry = array();
foreach ($arr as $a) {
foreach ($a as $key => $value) {
if (array_key_exists($key, $newArry)) {
//$newArry[$key] = array($value);
array_push($newArry[$key], $value);
} else {
$newArry[$key] = array($value);
}
echo "<br/> Key ".$key ." => Value ".$value;
//print_r($b);
}
}
print_r($newArry);
You can use a WP_Query, as page is simply a post type.
$args = array(
'post_type' => 'page',
'posts_per_page' => -1,
'orderby' => 'title',
'order' => 'ASC',
);
$query = new WP_Query( $args );
$pages = $query->posts;
See WP_Query documentation.

How do you target a specific page in Wordpress functions.php?

I am currently using the Multi Post Thumbnails plugin for Wordpress, but I only want the extra thumbnails provided by the plugin to show on one specific page. The plugin does not appear to natively support this functionality but it seems like something that would be pretty easy to add, I'm just not sure of the right way to go about it as I'm fairly new to Wordpress development.
The code for Multi Post Thumbnails is the following, which simply goes in functions.php:
if (class_exists('MultiPostThumbnails')) {
new MultiPostThumbnails(
array(
'label' => 'Secondary Image',
'id' => 'secondary-image',
'post_type' => 'page'
)
);
new MultiPostThumbnails(
array(
'label' => 'Tertiary Image',
'id' => 'tertiary-image',
'post_type' => 'page'
)
);
}
It seems to me it would just be a simple case of wrapping this in a check so that it only runs for a specific page ID, but I'm not quite sure how to go about doing that.
This is probably somewhat of a hack. To my knowledge post/page id's are not accessible from inside functions.php.
// get the id of the post/page based on the request uri.
$url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$post_id = url_to_postid($url);
// the id of the specific page/post.
$specific_post_id = 3;
// check if the requested post id is identical to the specific post id.
if ($post_id == $specific_post_id) {
if (class_exists('MultiPostThumbnails')) {
new MultiPostThumbnails(
array(
'label' => 'Secondary Image',
'id' => 'secondary-image',
'post_type' => 'page'
)
);
new MultiPostThumbnails(
array(
'label' => 'Tertiary Image',
'id' => 'tertiary-image',
'post_type' => 'page'
)
);
}
}
This is also probably a hack but it worked for me. I got stung by the AJAX 'post_id' back to the admin page once the image has been selected. My usage was for a slug but the function could easily be modified for a post ID.
function is_admin_edit_page( $slug ){
if( ( isset($_GET) && isset($_GET['post']) ) || ( isset($_POST) && isset($_POST['post_id']) ) )
{
$post_id = 0;
if(isset($_GET) && isset($_GET['post']))
{
$post_id = $_GET['post'];
}
else if(isset($_POST) && isset($_POST['post_id']))
{
$post_id = $_POST['post_id'];
}
if($post_id != 0)
{
$c_post = get_post($post_id);
if( $c_post->post_name == $slug )
{
return true;
}
}
}
return false;
}
if( is_admin_edit_page('work') ) {
new MultiPostThumbnails(
array(
'label' => 'Hero 1 (2048px x 756px JPEG)',
'id' => 'am-hero-1',
'post_type' => 'page'
)
);
}

Gettin atrribute thumbnail from node from a wordpress rss feed

I've been trying to get this seemingly easy peace of code to work.
I'm loading rss from a wordpress site and it all works fine except for the thumbnails. Since in the XML they are set as an attribute instead of a nodeValue i can't seem to get import them. (i've really tried a lot)
$rss = new DOMDocument();
$rss->load('http://goalprogramme.wordpress.com/feed/');
$feed = array();
foreach ($rss->getElementsByTagName('item') as $node) {
// in XML it looks like <media:thumbnail url="http://goalprogramme.files.wordpress.com/2014/01/dsc_0227.jpg?w=150"/>
//echo $node->getElementsByTagName('media:thumbnail')->item(0)->getAttribute('url');
//push items
$item = array (
'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,
'thumbnail' => $node->getElementsByTagName('media:thumbnail')->item(0)->getAttribute('url') // this line doesn't work !!!
);
array_push($feed, $item);
}
Any help would be greatly appreciated.
Thanks so much in advance!
Hours later i've created another piece of code that does work. If anyone needs it it, here it is:
$feed_array = array();
$feed = simplexml_load_file('http://goalprogramme.wordpress.com/feed/');
foreach ($feed->channel->item as $item) {
$title = (string) $item->title;
$description = (string) $item->description;
$link = (string) $item->link;
$date = (string) $item->date;
if ($media = $item->children('media', TRUE)) {
if ($media->thumbnail) {
$attributes = $media->thumbnail->attributes();
$thumbnail = (string)$attributes['url'];
}
}
$item = array (
'title' => $title ,
'desc' => $description,
'link' => $link,
'date' => $date,
'thumbnail' => $thumbnail
);
array_push($feed_array, $item);
}

insert product type from front end in wordpress

if(isset($_POST['uploadwine']))
{
global $wpdb,$woocommerce;
global $current_user;
$post_status = 'publish';
if(isset($_POST['postid']))
{
$postid=$_POST['postid'];
}else
{
$postid='';
}
$wine_post = array(
'post_title' => $_POST['wine_name'],
'post_status' => $post_status,
'post_author' => $current_user->ID,
'post_type' => 'Product',
);
if( empty($postid)){
echo $postid=wp_insert_post( $wine_post );
update_post_meta($postid, '_thumbnail_id', $_POST['aaiu_image_id'][0]);
$product_meta['year'] = $_POST['year'];
$product_meta['producer'] = $_POST['producer'];
#$product_meta['grapes_variety'] = $_POST['grapes_variety'];
$product_meta['area'] = $_POST['area'];
#$product_meta['tw_share'] = $_POST['Country'];
$product_meta['color'] = $_POST['Color'];
$product_meta['good_answer_for_the_smell_test'] = $_POST['Smell'];
$product_meta['good_answer_for_the_taste_test'] = $_POST['Taste'];
foreach($product_meta as $key =>$value)
{
update_post_meta($postid, $key, $value);
}
die;
}
I am posting product type from front end programatically. It is inserting product type into the database but not returning the post id. Instead it gives me this error "Call to a member function get_product() on a non-object in /srv/data/web/vhosts/www.wiine.me/htdocs/devbeta/wp-content/plugins/woocommerce/woocommerce-core-functions.php on line 32".
get_product() is woocommerce function may be hooked with wp_insert_post( $wine_post ) . it gives error after wp_insert_post funciton. so i can not add meta for this post.
Can anyone tell me why?

Resources