I am using the below code in functions.php to add custom query variables to my WordPress project.
<?php
function add_custom_query_var( $vars ){
$vars[] = "brand";
return $vars;
}
add_filter( 'query_vars', 'add_custom_query_var' );
?>
And then on the content page I am using:
<?php echo $currentbrand = get_query_var('brand'); ?>
So now I can pass a URL like:
http://myexamplesite.com/store/?brand=nike
and get nike in result.
How can I pass multiple values for a brand. So I would like to have 3 values for brand say, nike, adidas and woodland.
I have tried the following and none of them works:
http://myexamplesite.com/store/?brand=nike&brand=adidas&brand=woodland
It just returns the last brand, in this case woodland.
http://myexamplesite.com/store/?brand=nike+adidas+woodland
This returns all three with spaces. I kind of think this is not the correct solution. So may be there is a correct way to pass multiple values for a query variable and retrieve them in an array may be so that a loop can be run.
Usually you would pass the parameter like ?brand[]=unresponsibleCompany1&brand[]=otherBrandThatDoesNotCareMuch&brand[]=bunchOfCriminals .
In your WordPress PHP code, then get_query_var( 'brand' ) will return you an Array.
Everything else sounds like a relatively cheap but costy workaround.
You will need to pass query parameters in this way;
brand1=nike&brand2=adidas&brand3=woodland
So, different key for each brand
On the page, recieving values
$params = $_GET;
$brands = array();
foreach($params as $k=>$v) {
if(substr($k,0,5)=="brand") {
$brands[] = $v;
}
}
Alternatively
Using your 2nd method
http://myexamplesite.com/store/?brand=nike+adidas+woodland
$brands = explode(" ", $_GET['brand']);
Alternative method looks easier 🙂
Related
I'm trying to merge 2 arrays in PHP and then sort them.
I'm pulling data from WordPress database ( tags and categories ) and I need to merge them and sort them properly.
Code looks similar to this:
$categories = [
'<a>WordPress Tips</a>',
'<a>SEO Tips'</a>,
'<a>Development Tips</a>'
];
$tags = [
'<a>WordPress</a>',
'<a>SEO'</a>,
'<a>Development</a>'
];
$taxonomies = array_merge($categories, $tags);
sort($taxonomies);
Since I need to loop through $taxonomies array and print them with anchors included ( every one of those must have a valid URL to itself ), I don't get a proper sorting result. However, as soon as I 'strip out' all the tags around these items, sorting works as it should, but I don't get URLs that I need, only string / text.
Could someone suggest a better sorting algorithm which would sort these items properly with html elements included around them? Thanks!
You need to do custom comaprision to make it work using usort() and strip_tags()
<?php
$taxonomies = array_merge($categories, $tags);
print_r($taxonomies);
function cmp($a, $b){
$data1 = strip_tags($a);
$data2 = strip_tags($b);
return ($data1 < $data2) ? -1 : 1;
}
usort($taxonomies, "cmp");
print_r($taxonomies);
Output:-https://eval.in/934071
Since you mentioned that the tags stripped version works, a simple way might be to use them as the keys in the sort. Something like this, for instance :
$taxonomies = array_merge( $categories, $tags );
$toSort = [];
foreach($taxonomies as $tax) {
$toSort[strip_tags($tax)] = $tax;
}
ksort( $toSort );
print_r( $toSort );
Which will give the sorted array and you can just use the values in there. Maybe there's better options but this comes to mind off the top of my head..
EDIT : uasort with a comparision function that actually compares the stripped versions might be better, after looking at other answers here.
I'm working on a PHP project and would love to get some help on variables.
I have a function that looks like this:
function custom_get_tour_nearest_booking_dates( $tour_id, $limit = 2, $exclude_booked_tickets = false ) {
$result = array();
if ( $tour_id < 1 ) {
return $result;
}
The database holds a set of products, each of these with a unique ID made up by numeric values, like 1233,2355,6532 and so on.
If I want to display the characteristics of one of these products, how do I link the ID to the variable $tour_id?
Somewhere you call that method: custom_get_tour_nearest_booking_dates(4);
Like the example above, 4 is the tour_id. Besides that, your method is kinda useless.
I made a simple import script and I'm trying to programatically save 3 custom attributes (att1, att2, att3) together with all other info (name, description, price, category..).
So basically I have:
public function insert_product($data) {
$product = Mage::getModel('catalog/product');
try {
$sku = $data['code'];
if ($this->prodottiImportati[$sku]) {
$sku = $data['code'] . '-1';
}
$this->prodottiImportati[$sku] = true;
$product->setSku($sku);
$product->setName($data['name']);
$product->setDescription($data['desc']);
$product->setShortDescription($data['short_desc']);
$product->setManufacturer('');
$product->setPrice($data['price']);
$product->setTypeId('simple');
$product->setAttributeSetId($this->attributeSet);
$categorie = $this->get_categories($data);
$product->setCategoryIds($categorie);
$product->setWeight($data['peso']);
$product->setTaxClassId(2); // taxable goods
$product->setVisibility(4); // catalog, search
$product->setStatus(1); // enabled
$product->setWebsiteIds($data['store_id']);
$stockData = $product->getStockData();
$stockData['qty'] = $data['qty'];
if ($data['quantita'] > 0) {
$stockData['is_in_stock'] = 1;
} else {
$stockData['is_in_stock'] = 0;
}
$stockData['manage_stock'] = 1;
$stockData['use_config_manage_stock'] = 0;
$product->setStockData($stockData);
$product->setIsMassupdate(true)->setExcludeUrlRewrite(true);
$product->save();
$productID = $product->getId();
} catch(Exception $e) {
echo ($e->getMessage());
}
return $productID;
}
First thing I tryed was adding a
$productID = $this->insert_product($data);
Mage::getSingleton('catalog/product_action')->updateAttributes(
array($productID), array(
'att1' => $data['att1'],
), $data['store_id']);
So basically updating things after the insert function was called, using the ID got after the insert. store_id is the ID of the store in that given language. Didn't save anything.
Second attempt, I follwed this: Magento add custom options with programmatically importing products
I tryed that within the insert_product function and also outside after $productID = $this->insert_product($data); Neither worked.
Last I tryed a magical $product->setAtt1('value'); witin the insert_product function, not sure how Magento would understand how to set att1 that way, but...you know, I read it somewhere and I gave it a try ;)
att1, att2 and att3 are spelled lowercase, althoug they have an uppercase label (think that dosen't matter here), they are part of an attribute group (I'm passing it with $product->setAttributeSetId($this->setAttributi)) and they are all multiple selection attributes, so I could in teory pass multiple values to them.
I'm sure I'm missing something on the way. Can anyone help?
After 10 more minutes since I wrote here, I was able to find the way. I took me forever to solve it.
The clue of this is that you have to add attributes ID, not values. That happens at least for me with multiple selection attributes, not sure if it's true all the time.
Here is how I did:
In the function insert_product I added:
$optionId = $this->get_option_id_by_code('att1', 'Value of the attribute you need to add');
$product->setAtt1($optionId);
So if yor attribute is named, let's say "brand" it will be:
$optionId = $this->get_option_id_by_code('brand', 'Nike');
$product->setBrand($optionId);
If your attribute can have multiple values, you need to change the code above to:
$optionId = array();
foreach ($myAttributesArray as $someValues) {
$optionId[] = $this->get_option_id_by_code('att1', $someValues);
}
$product->setAtt1($optionId);
The foreach is just an example, you need to loop through your mutiple values and get the respective ID and add them all toghether with setAtt1 passing them as an array. I'm working on an improved version where the get_option_id_by_code function does all at once in a more efficient way. This is kust a "basic" version that works, feel free to make it fancy and smart.
Then I created an other function called get_option_id_by_code like this:
protected function get_option_id_by_code($attrCode, $optionLabel) {
$attrModel = Mage::getModel('eav/entity_attribute');
$attrID = $attrModel->getIdByCode('catalog_product', $attrCode);
$attribute = $attrModel->load($attrID);
$options = Mage::getModel('eav/entity_attribute_source_table')
->setAttribute($attribute)
->getAllOptions(false);
foreach ($options as $option) {
if ($option['label'] == $optionLabel) {
return $option['value'];
}
}
return false;
}
To be honest I found this with a collage of other sources / authors, so I need to be thankful to a bunch of smarter programmers here and there, since it took a while for me to strouggle with this simple task I wrote the solution here hoping to help you guys. Thanks!
I am trying to pass the post ids to the function's query->set and function will return the posts.
add_action( 'pre_get_posts', 'query_booked_posts' );
function query_booked_posts( $query ) {
if ( $condition ) { //the condition
if ( is_home() && $query->is_main_query() )
$results = $wpdb->get_col($wpdb->prepare( "SELECT booked_id FROM $wpdb->userbooking WHERE userid = %d",$current_user_id));
foreach($results as $result){
$results_separated = $result.',';
}
$query->set ('post__in', array($results_separated)); // pass results (post ids) to post__in
return $query;
}
}
After this, the function returns nothing.
If I do $query->set ('post__in', array(45,121));, the query will return the posts of id 45 and id 121, so the query works fine.
But I want to make $results_separated pass the post ids like 45,121,132 to the query, and then $query->set ('post__in', array($results_separated)); will work correctly.
How can I make this happen?
pre_get_posts reference
I guess you have actually a PHP problem. When you do array($results_separated) you're basically creating an array from a string that looks like this: "12,114,56,". By doing that, PHP is creating an array like this:
array(
0 => "12,114,56,"
)
And obviously WordPress cannot find any posts with such ID! What you want is actually an array like this:
array(
0 => "12",
1 => "114",
2 => "56"
)
And actually that's what get_col() returns, so you just need to pass $results to set() function:
$query->set ( 'post__in', $results );
EDIT: Actually I realised that your problem is when you call $wpdb->get_col(...), because it's interfering with the $query you will execute later on... Those variables are using some other global variables that probably get overriden, and that's why you're not getting any results...
Except the extra array() over $results_separated, in my case I had to apply
if (!$query->is_main_query()) {
return $query;
}
at the top of my function (found it in, otherwise, queries inside would be executed for several times and not properly.
Comments in the answer helped me to figure this out.
I am creating custom emails to be sent to customers wanting to share their cart with others. So far, I have each product's quantity, SKU, price, path (node/XYZ), and title. The last item I need in the email is the product's image path.
I found all the other information with the following:
$order = commerce_cart_order_load($user->uid);
foreach($wrapper->commerce_line_items as $d => $line_item_wrapper) {
$sku = $line_item_wrapper->line_item_label->value();
//...
Printing out the following I was able to see a protected "data" property for the wrapper object:
print_r($line_item_wrapper->commerce_product);
Then, I tried finding the getter method for the field_image property with the following:
print_r($line_item_wrapper->commerce_product->getPropertyInfo('field_image');
I ended up here with entity_metadata_field_verbatim_get() but I don't know what parameters to pass. Also, in the last print statement above I didn't see anything else of value.
I'm wondering if I need to query for this data, and what table / columns to query for? Or maybe use something like node_load()? However, i'm not finding it too easy to find the node ID from the line item wrapper.
I was able to solve the above problem with this code:
$order = commerce_cart_order_load($user->uid);
$wrapper = entity_metadata_wrapper('commerce_order', $order);
$result = array();
foreach($wrapper->commerce_line_items as $d => $line_item_wrapper) {
$product = array();
$product['quantity'] = $line_item_wrapper->quantity->value();
$product['sku'] = $line_item_wrapper->line_item_label->value();
$product['path'] = $line_item_wrapper->commerce_display_path->value();
$product['price'] = $line_item_wrapper->commerce_unit_price->amount->value();
$product['title'] = $line_item_wrapper->commerce_product->title->value();
$product['image'] = $line_item_wrapper->commerce_product->field_image->value();
$product['image'] = $product['image'][0]['filename'];
array_push($result, $product);
}
I have to say, finding all these discrete functions was quite difficult. I did not find any clear documentation about Drupal Commerce metadata_wrappers. If anyone could provide further information I'd love to take a look.
In general, I used a lot of print_r(); to find these values.