Set default first attributes for woocommerce variations - php

I found this question, but no one gave a working answer:
Woocommerce Set Default Variations
What is mentioned here doesn't work anymore and I don't understand what the error is:
https://quadlayers.com/default-product-attributes-woocommerce/
Maybe someone knows how to make sure that when entering a variable product, at least some option is selected and the add to cart button is active?
The code that unfortunately no longer works:
add_action('woocommerce_before_single_product_summary', 'quadlayers_product_default_attributes');
function quadlayers_product_default_attributes() {
global $product;
if (!count($default_attributes = get_post_meta($product->get_id(), '_default_attributes'))) {
$new_defaults = array();
$product_attributes = $product->get_attributes();
if (count($product_attributes)) {
foreach ($product_attributes as $key => $attributes) {
$values = explode(',', $product->get_attribute($key));
if (isset($values[0]) && !isset($default_attributes[$key])) {
$new_defaults[$key] = sanitize_key($values[0]);
}
}
update_post_meta($product->get_id(), '_default_attributes', $new_defaults);
}
}
}

You should have the option to select a 'Default Form Values:' inside variations tab which lets you select the default option for your variant.
Like this:

Related

Check if product has specific attributes set to it, then show additional div if true

I am trying to create a function to show additional product information if requirements are met dependent on whether some attributes are set or not on specific products. For this I am using two attributes called 'pa_storlek' and 'pa_djurart'. Seems to me everything should be working but no matter what I do I just keep getting the else value (Inte X-Small).
I need to check the two attributes together, meaning that if I get both attributes values at the same time the statement should be valid, and - if not, it should show the else output.
Anyone has an idea? Been looking around alot but can't seem to find another question like mine..
// X-Small dogs list
add_action( 'woocommerce_single_product_summary', 'x_small_dogs', 90 );
function x_small_dogs() {
global $product;
$product_attributes = $product->get_attributes();
// Get the product attribute value
$size = $product->get_attribute('pa_storlek');
$animal = $product->get_attribute('pa_djurart');
// If product has attribute 'size = x-small' and 'animal = hund'
if( strpos($size, 'x-small') && strpos($animal, 'hund') ) {
echo '<div class="">X-Small</div>';
} else {
echo '<div class="">Inte X-small</div>';
}
}
If strpos find the string starting at the first character, return 0 (index position) and it is evaluated like false.
So try
if( strpos($size, 'x-small')!==false && strpos($animal, 'hund')!==false) {

Magento 2 get attribute values

I have created a product attribute in Magento 2 that is a dropdown.
I have given this attribute many options. How can I output all these possible options attached to the attribute code/name? I can only find examples for Magento 1 or those that are assigned to a product. I want to get all the options assigned to the attribute.
This is what I tried before realising it wasnt for Magento 2.
<?php
$attributeId = Mage::getResourceModel(‘eav/entity_attribute’)->getIdByCode(‘catalog_product’,’color’);
$collection = Mage::getResourceModel(‘eav/entity_attribute_option_collection’)
->setPositionOrder(‘asc’)
->setAttributeFilter($attributeId)
->setStoreFilter(0)
->load();
print_r($collection->getData());
?>
you can try below code
function getAttrAllOptions() {
$eavConfig = $this->objectManager->get('\Magento\Eav\Model\Config');
$attribute = $eavConfig->getAttribute('catalog_product', 'color');
$alloptions = $attribute->getSource()->getAllOptions();
foreach($alloptions as $option) {
$label = $option['label'];
$AllOptionsArr[$label][] = $option['value'];
}
return $AllOptionsArr;
}
hope this helps!

Select woocommerce chosen shipping method price

I'm trying to select the chosen_shipping_method price in woocommerce using this code:
$packages = WC()->shipping->get_packages();
foreach ($packages as $i => $package) {
$chosen_method = isset(WC()->session->chosen_shipping_methods[$i]) ? WC()->session->chosen_shipping_methods[$i] : '';
}
echo $chosen_method;
the code works, but it prints the ID, and i cannot figure out how to make it print out the price.
Here's package structure:
What i get with my code is table_rate_shipping_shipping_self_install, but what i need is the cost for the selected element, and not the id.
i tried to change the code like this:
foreach ($packages as $i => $package['rates']) {
$chosen_method = isset(WC()->session->chosen_shipping_methods[$i]) ? WC()->session->chosen_shipping_methods[$i] : '';
}
But it printed out the id, same as before.
Any ideas? sorry i'm a bit new to php.
Thanks in advance
Did you try this inside your foreach loop?
$rate = $package['rates'][$chosen_method]->cost;
If yo need to get price of shipping method that was chosen by user and stored in session, you should try this:
$chosen_shipping_method_price = WC()->session->get('cart_totals')['shipping_total'];

Create a new Prestashop cart in custom php

In Prestashop, I've created a custom form where I show a list with all products and the user can fill the corresponding quantities. By submitting the form, I clear the cart and fill it with the new values and finally redirect to the checkout page.
Everything's working fine, but only when the cart already exists. In a case of an empty cart (cart_id==null), I cannot add the products. I tried with several ways to create a $cart but I didn't manage to do so.
I don't get any exceptions, the code is executed without errors, it's just that at the end, in the checkout page, the cart remains empty; I repeat, only when the cart was already empty. In the case of a cart with products in it, then the process is just perfect!
I would appreciate some help on this.
Here is my small controller that gets the products and quantities from the form and adds them in the cart:
include('../../config/config.inc.php');
include('../../header.php');
// Filling the array of products
$products = array();
foreach ($_POST as $key => $value)
if (substr($key, 0, 9) === 'quantity_')
$products[substr($key, 9)] = $value;
// First of all, we remove all products
$prods = $cart->getProducts();
foreach ($prods as $prod)
$cart->deleteProduct($prod['id_product']);
// Adding the new products
foreach ($products as $product_id => $quantity)
if ($quantity > 0)
$cart->updateQty($quantity, $product_id);
// Redirecting to the checkout page.
header("Location: " . $_POST['redirect']);
exit();`
Thank you in advance!
I had the same problem with Prestashop not correctly creating a new cart upon calling the CartCore in many different ways - neither context or direct calls did work out.
Found this gem from someone else over here:
// get cart id if exists
if ($this->context->cookie->id_cart)
{
$cart = new Cart($this->context->cookie->id_cart);
}
// create new cart if needed
if (!isset($cart) OR !$cart->id)
{
$cart = new Cart();
$cart->id_customer = (int)($this->context->cookie->id_customer);
$cart->id_address_delivery = (int) (Address::getFirstCustomerAddressId($cart->id_customer));
$cart->id_address_invoice = $cart->id_address_delivery;
$cart->id_lang = (int)($this->context->cookie->id_lang);
$cart->id_currency = (int)($this->context->cookie->id_currency);
$cart->id_carrier = 1;
$cart->recyclable = 0;
$cart->gift = 0;
$cart->add();
$this->context->cookie->id_cart = (int)($cart->id);
$cart->update();
}
This is working for me now. As you see it goes a little more in depth than just asking the context to retrieve or create a new cart. hth.
You probably need to include this line when you are outside of a class
$context = Context::getContext();
And then add a cart variable that defines cart attributes ( in ur case assigns a id )
$cart = $context->cart; // gets the cart id or creates a new one
Should work fine now
BR's ( dont forget to accept the answer if it helps you :) )
As a complement to previous posts.
If you set that configuration : Configuration::updateValue('PS_CART_FOLLOWING', 1) (display the last cart of the customer instead of creating a new one each time).
You will always get the cart id $this->context->cart->id at NULL when trying to create a new cart at the customer's first log in (after creating a new account) using the following code:
if (is_null($this->context->cart)) {
$this->context->cart =
new Cart($this->context->cookie->id_cart);
}
I manage to solve the problem by adding some code to after the invalid cart creation.
/**
* Manage the possible errors when trying to create
* a new cart for a customer.
*
* The new cart is saved in the current context ($this->context->cart).
*/
private function createCart()
{
if (is_null($this->context->cart)) {
$this->context->cart =
new Cart($this->context->cookie->id_cart);
}
if (is_null($this->context->cart->id_lang)) {
$this->context->cart->id_lang = $this->context->cookie->id_lang;
}
if (is_null($this->context->cart->id_currency)) {
$this->context->cart->id_currency = $this->context->cookie->id_currency;
}
if (is_null($this->context->cart->id_customer)) {
$this->context->cart->id_customer = $this->context->cookie->id_customer;
}
if (is_null($this->context->cart->id_guest)) {
if (empty($this->context->cookie->id_guest)){
$this->context->cookie->__set(
'id_guest',
Guest::getFromCustomer($this->context->cookie->id_customer)
);
}
$this->context->cart->id_guest = $this->context->cookie->id_guest;
}
if (is_null($this->context->cart->id)) {
$this->context->cart->add();
$this->context->cookie->__set('id_cart', $this->context->cart->id);
}
}
After initializing the cart that way, I'm now able to add products to the cart with no problem.
Good success everyone

get quote's product attribute

Hi I'm trying to get a product attribute admin value or id (since it's multilanguage) from the cart items. I've tried many versions of code like this one:
$session = Mage::getSingleton('checkout/session');
foreach ($session->getQuote()->getAllItems() as $item) {
$_product = Mage::getModel('catalog/product')->load($item->getId());
$attribute = $_product->getAttribute('producttype');
}
But I only ever get false or null. Also how can I be sure to not get the store specific language value, but the attributes admin value/id? Maybe there's an even better way to read out the item attributes directly from the quote items without having to load the product first? Thanks in advance!
Solved with:
$session = Mage::getSingleton('checkout/session');
foreach ($session->getQuote()->getAllVisibleItems() as $_item)
{
$_product = Mage::getModel('catalog/product')->load($_item->getProductId());
$attributeId = $_product->getProducttype();
}
and comparing by value ID instead of text.
If you need to get the product's value for a specific shop, while the items in the quote belong to a different store view, you can do the folowing:
$_product = Mage::getModel('catalog/product')
->setStoreId($adminStoreId)
->load($item->getId());
$value = $_product->getData('producttype');

Categories