Getting two arrays from URL parameters and combine them together (PHP) - php

I'm trying to get two arrays "Product IDs and Product Quantity" from URL parameters written like this: id[]=p1&qty[]=12&id[]=p2&qty[]=12.
My code is:
<?php
$id = $_GET["id"];
$qty = $_GET["qty"];
foreach ($id as $product) {
echo "<br>Product ID is: $product and Quantity is: $qty";
};
?>
The purpose of the code is to assign quantity to each ID in a single line of code.
I will appreciate your guidance for the exact example in my question as I've seen similar questions but with other examples and purposes.
Thank you very much in advance!
Trying to assign product quantity to each product ID.

Related

Using wc_get_product() with a PHP variable for product ID

I'm building out custom landing pages for products in WooCommerce and I'd like to get the product price amongst other things in order to display them on the landing page.
Each landing page has some custom fields which allow the WP Admin to add in content, for the landing page as well as the product ID, which will then be used to generate the product price, checkout URL etc..
I can't get the wc_get_product(); to work with my custom field or a variable built off that. It only works when I use a straight ID. I think there's something I'm not understanding about how variables work within PHP. Here's my code.
<?php
//Gets the course ID from the custom field entered by user
$courseID = the_field('course_id');
// This line is where the problem is...
$_product = wc_get_product('$courseID');
// If I replace the line above with this line
// $_product = wc_get_product('7217');
// everything works great, but that does not let
// each landing page function based on the custom fields where the user determines
// the product ID they are selling on that landing page.
// Get's the price of the product
$course_price = $_product->get_regular_price();
// Output the Course price
?> <span class="coursePrice">$<?php echo $course_price;?></span>
Update
I get the following error using wc_get_product( $courseID ); or get_product( $courseID );:
Fatal error: Call to a member function get_regular_price() on a non-object in ...
Update related to your recent comment. The 2 ways to explore:
1) Instead of you should try to use to get the product object (avoiding the error):
$courseID = the_field('course_id');
// Optionally try this (uncommenting)
// $courseID = (int)$courseID;
// Get an instance of the product object
$_product = new WC_Product($courseID);
2) Alternatively if this doesn't work, you should try to use get_post_meta() function to get the product price (or any product meta data) this way:
<?php
//Gets the course ID from the custom field entered by user
$courseID = the_field('course_id');
// Get the product price (from this course ID):
$course_price = get_post_meta($courseID, '_regular_price', true);
// Output the Course price
?> <span class="coursePrice">$<?php echo $course_price;?></span>
This time you should get displayed the price with one or the other solutions.
Update: May be Also you need to convert $courseID to an integer variable.
Because you need to use your variable $courseID inside wc_get_product() (without the 2 ') function this way:
<?php
//Gets the course ID from the custom field entered by user
$courseID = the_field('course_id');
// Optionally try this (uncommenting)
// $courseID = (int)$courseID;
// Here
$_product = wc_get_product( $courseID );
$course_price = $_product->get_regular_price();
// Output the Course price
?> <span class="coursePrice">$<?php echo $course_price;?></span>
This should work now.
You can try this out :
$courseID = the_field('course_id');
$product = get_product( $courseID );
I figured out the answer after running through the possible solution routes that #LoicTheAztec supplied in his response. None of these worked and so I assumed something else was up.
I use Advanced Custom Fields to add custom fields in the back end and I was using ACF's the_field() in order to create my variable. That is incorrect usage of that function as it's designed to display the field, (it's basically using php's echo). To work with these custom field's you need to use ACf's get_field() which is to use it to store a value, echo a value and interact with a value.
Once I switched to setting my $courseID to this..
$courseID = get_field('course_id');
Everything worked. My code worked, and all #LoicTheAztec's code approaches also worked.

return woocommerce item names from cart only if they are a certain variation

I'm more or less a total newbie to php. My goal is to get the names of items from the logged in user's cart and dynamically populate a GravityForms template with the information. I've successfully managed to do that with the code below, but there are three things that I'm failing to do. 1: I only want to populate the form with all items of a certain variation. 2: the echo function will list all of the item names, but not inside the relevant field, and the return function will populate the field, but only with the first item name. 3: I'd like to have the output items listed with some form of separator in between each item name. Here's what I have so far:
<?php
add_filter( 'gform_field_value_beat_names', 'beat_names_function' );
function beat_names_function( $value ) {
global $woocommerce;
$items = $woocommerce->cart->get_cart();
foreach ($items as $item) {
$product_variation_id = $item['variation_id'];
$license_id = new WC_Product($product_variation_id);
$license_string = $license_id->get_formatted_name();
$beat_id = $item['data']->post;
$beat_name = $beat_id->post_title;
if (strpos($license_string, 'basic') !== false) {
echo $beat_name;
}
}
}?>
As you can see, I'm attempting to use strpos to isolate the particular item variation I want to target, using a certain word found in the name of the variation option, being "basic". I'm sure there's a more secure way of doing that, but it works for now. The problem lies with the return function I set up inside the conditional strpos statement, being that it will still just return the entire list of cart items, as opposed to only the items that I'm trying to isolate with the strpos conditional.
The ultimate goal is to create a license agreement that is dynamically populated with the relevant information, including the names of the items being licensed. The item variations are different license options that I have available for the products in my store. The purpose of the above code is to filter cart items by license type so that the wrong item names don't get listed on the wrong license agreement at checkout.
Any tips would be appreciated
Figured it out after some more tinkering. I broke it down step by step to help anyone as clueless as I am
add_filter( 'gform_field_value_basic_beat_names', 'basic_beat_names_function' );
function basic_beat_names_function( $value ) {
global $woocommerce;
$items = $woocommerce->cart->get_cart();
// the item names you want will be stored in this array
$license_check = array();
// Loop through cart items
foreach ($items as $item) {
// get the id number of each product variation in the cart. this won't work for "simple" products
$product_variation_id = $item['variation_id'];
// translate that id number into a string containing the name of the product, and the options applied to the product
$license_id = new WC_Product($product_variation_id);
$license_string = $license_id->get_formatted_name();
// check to see if the word "basic" is found anywhere in that string. "basic" is contained in the name of the product option being targeted
if (strpos($license_string, 'basic') !== false) {
// if the above condition is met, fetch the name of any products in the cart that have that option applied. The product name will be fetched from the title of the product's page
$beat_id = $item['data']->post;
$beat_name = $beat_id->post_title;
// store the retrieved product names in the $license_check array
$license_check [] = $beat_name;
}
}
// pull the stored product names from the $license_check array, and format them using implode and concatenation, then return the final result to the form field
return "\"" . implode("\", \"", $license_check) . "\"";
}
As a warning, the strpos method is a little hacky. It'll only work properly if your string is specific enough to target ONLY the option you're looking for.
As an example, here's the format for the product variation string being fed into the strpos function:
item-name-option-one-name-option-two-name – variation #xxx of item page title
So, if you want to filter items ONLY by option one, your safest bet would be to write the strpos function like so:
if (strpos($license_string, 'option-one-name') !== false) {
//do something
}
When all is said and done, the final result should look like: "item1", "item2", "item3", etc.
Then, to do the same with any other option, and output the result in a different field, or separate form altogether, I'll just duplicate this code, and replace any mention of the word "basic" with some different unique string contained in the other option. Don't forget to configure the gravity forms field as necessary too.

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');

get basket product id in observer

I've set an observer for sales_quote_add_item in order to clear the cart whenever a certain product is going to be added (it's only supposed to be ordered alone).
I'm just not sure on how to get the product ID of the product that is about to get added. With some trial & error I've come up with this:
$tmp = $observer->getEvent()->getQuoteItem()->getData();
echo $tmp['product_id'];
Which seems to be quite an ugly solution. I'm sure there is some shortcut or proper function to call for this, any ideas?
Your solution is good enough
$productId = $observer->getEvent()->getQuoteItem()->getProductId();
You may load product after if is needed
$product = Mage::getModel('catalog/product')->load($productId);
Use the following code to get product id of quote item data
$cart = Mage::getModel('checkout/cart')->getQuote();
foreach ($cart->getAllItems() as $item)
{
$productId = $item->getProduct()->getId();
}
Hope this helps to you.

Get product id in magento

In magento,i want to add quick look feature like this http://www.timberlandonline.co.uk/on/demandware.store/Sites-TBLGB-Site/default/Link-Category?cgid=men_footwear_boots.I have added a hidden input & a div in list.phtml.If i click the div of any product javascript returns product id of first product in that category page.But it should return product id of the selected div.
You need to look into this page (<path_to_your_template_folder>/template/catalog/product/list.phtml) carefully. You will find the following lines of code in different places of this page only:-
$_productCollection = $this->getLoadedProductCollection();
foreach ($_productCollection as $_product):
$reqProductId = $_product->getId();
endforeach;
If you carefully match the above code & the code in the above-mentioned page, you will know that you need to use the variable "$reqProductId" properly in your required "INPUT" element of type "hidden". So you will require it to do your part in the main "foreach" loop.
Hope it helps.
Try below code to get currently loaded product id:
$product_id = $this->getProduct()->getId();
When you don’t have access to $this, you can use Magento registry:
$product_id = Mage::registry('current_product')->getId();
Also for product type i think
$product = Mage::getModel('catalog/product')->load($product_id);
$productType = $product->getTypeID();

Categories