How to check if an order number exists in woocommerce? - woocommerce

In my WooCommerce store, I have an input field where I want the user to enter the order number. When validating this field, I need to check if that order number actually exists in WooCommerce.
From this question, it seems like the WooCommerce order_number might not always be the same as the order_id (which is always the same as the post_id).
So I can't use wc_get_order($the_order) function since the documentation states that it wants the post_id in the $the_order parameter.
I can't find a specific function to get the order by the order number (neither in the documentation nor the code in github).
I'm fairly new to WooCommerce, so maybe I am missing something. Is there a way to do this at all? Or is the wc_get_order mis-documented?
I've done a lot of googling and searching here on stack overflow, but I really can't find the answer to this! Any help is appreciated.
PS: I suppose I could get all orders and loop through them one by one checking if the number matches, but I was hoping to find a simpler solution to this :D

You may try this if statement to see if given ID (number) is an Order Number or not:
function is_it_a_shop_order($givenNumber)
{
if(get_post_type($givenNumber) == "shop_order")
{
echo "yes this is a valid order number";
}
else
{
echo "no go away";
}
}
Wordpress stores all posts (pages, orders, products etc.) in wp_posts table and orders are stored with post type named "shop_order".
I tested the code. I hope this will help you. Have a good day.

The reason you're struggling to find anything about this in the documentation is because WooCommerce has no native concept of an order number. The ID is the order number.
What store owners tend to find however is that order IDs don't increase sequentially. There can be a large jump in ID between one order and the next because of the way WordPress handles posts. Often users will install a plugin to address that. It's those plugins that introduce the differentiation between order IDs and what they refer to as the order number.
Here's an example of one such plugin: https://en-gb.wordpress.org/plugins/woocommerce-sequential-order-numbers/
Included in the documentation is an example of how to find an order by its number. If you have one of these plugins installed, you'll simply need to lookup how the plugin in question resolves numbers to IDs.

Send the order number through the wc_get_order call. If the returned array is empty, the order number does not exist.
$bOrderExists = DoesOrderExist($OrderNumber);
function DoesOrderExist($OrderNumber)
{
$orderq = wc_get_order($OrderNumber);
if(empty($orderq))
return 0;
return 1;
}

Related

WooCommerce - Change customer order after it has been placed and paid

Using three plugins:
WooCommerce
Subscriptio
WooEvents
I have created a product which allows for a customer to pay for an event over five instalments.
A customer has placed an order and made their first of the five payments via PayPal and has then contacted me to advise they have booked the wrong event.
The correct event is exactly the same except the dates are a month sooner.
I have added the following snippet to be able to edit 'processing' orders:
add_filter( 'wc_order_is_editable', 'wc_make_processing_orders_editable', 10, 2 );
function wc_make_processing_orders_editable( $is_editable, $order ) {
if ( $order->get_status() == 'processing' ) {
$is_editable = true;
}
return $is_editable;
}
From the order screen within the back-end of WordPress I can see that the the order can be edit by way of removing the product from the order or editing the meta data and cost.
The correct product that should have been ordered has a different product/variation ID.
My question is simply:
Should I remove the incorrectly ordered product from the order and add the correct product (both have the same properties with the exception of the courses dates); or
Should I just change the meta data and increase the stock levels for the incorrectly product back to X and reduce the stock level for the correct product?
Your second option is much better. Change the meta from database if its accessible and then manage the stock accordingly.
I have not yet done this, but according to this exchange ...
How can I add a product to an existing and paid Woocommerce order?
... you can set the order status to "On Hold" and make changes to the order itself. I presume you would then return the status to "Processing".
I would expect that if the application permits those changes, then it would be doing the background meta changes to inventory levels, etc., and spare you the problem of doing so (and the potential errors that may occur when messing with the data tables outside of the application).
Like I said, I haven't done this. But it might be worthwhile doing a little test to make sure it works as it seems to be described in the answer to the other question.
J

Wordpress order categories

I have a Wordpress site where a lot of the categories are peoples names. The slug becomes john-smith fred-wilkinson etc by default. So the category list is in alphabetical order by their first name. I would like them to list by last name.
I could get the authors/editors to change the slug to wilkinson-fred etc but I would rather have a solution that they don't have to alter the default slug.
I know there are plug-ins that you can drag and drop to any order you want. Again this relies on the author/editor putting it in the right place.
My slugs currently look like this
john-smith
fred-wilkinson
Alan-t-jones
etc
I have other categories that I don't want to alter. I only want to reorder where the parent category is "artist".
Any ideas? If I put wilkinson-fred in the description field can I sort on that?
Thanks
I assume that you want to change the order of wp list categories function output (maybe make it a little clearer in your future SO questions!). If that's so, I think you have two options here:
1) Hijack the orderby parameter as mentioned in this answer by #Chris_O at Wordpress Stackexchange:
There is an unused column, term_order, in the wp_term_relationships table that you can use to assign a custom order to the terms within your taxonomy. The order is set at 0 by default and it will take a custom query to get the order back and another solution to set the order.
Although as #Kaiser mentions in the comments to the answer, this sollution is a little hacky as it's not meant to be used this way and its implemantation may change in future releases of Wordpress.
2) Store the output of the function in varible (echo => false under $args), manipulate the output and print the resulting array. This is the way I would choose as it makes you more in control of the situation.

Apachesolr query - filter by text in fields

I'm constructing an apachesolr query in my Drupal module programmatically and have had success with some aspects, but am still struggling with others.
So far, I have been able to construct a query that can search for specific text and limit the results based on terms to be filtered by with the following code:
$subquery_region->addFilter('tid', $term->tid);
$query->addFilterSubQuery($subquery_region, 'OR', 'AND');
What I'd like to achieve next is to be able to narrow the search further by adding a filter for finding certain text within a specific field in the node. Has anyone been able to do this.
I've been researching online and have tried lots of different ways such as adding the filter directly to the main search query
$query->addParam('fl', 'ss_my_field');
$query->addFilter("ss_my_field", "field_substring_to_search_for");
As well as breaking that out into a subquery to add to the main search query
$subquery_test = apachesolr_drupal_query("Test");
$subquery_test->addParam('fl', 'ss_my_field');
$subquery_test->addFilter("ss_my_field", "field_substring_to_search_for");
$query->addFilterSubQuery($subquery_test, 'OR', 'AND');
But none of these are working. They are returning an empty set, even though I know the substring exists in the field I'm adding as a filter and it has been indexed. I have verified through the apachesorl views module that the search index has been populated with that field and can see the substring exists.
Is there anything wrong with my syntax or the way I'm building the query?
If you know how to add filters for searching for text within certain fields, please share! It may not even be done with the addFilter function, but that's all I have been trying so far.
Thanks!
First you have to create an index for that specific field.
function hook_apachesolr_update_index(&$document, $node) {
$document->ss_your_field_name = $node->your_field_name;
}
where ss_* is the pattern.
ss_* -> String
is_* -> Integer
im_* -> Integer, Multivalued
After that you have to
1. delete the index - admin/settings/apachesolr/index
2. re-index the content
3. run the cron
4. check the filter that you created - admin/reports/apachesolr/index
Then, you can add filters
$query->addFilter("ss_your_field_name", "value");
Hope this helps you.
function hook_apachesolr_modify_query(&$query, &$params, $caller){
$subquery = apachesolr_drupal_query();
$subquery->add_filter("ss_my_field", "field_substring_to_search_for");
$query->add_subquery($subquery, "AND");
}

How to display the total amount of posts?

What's the best way to display in a block the total amount of posts and comments of my entire drupal website?
thanks
The quick and dirty way:
Ensure that you have PHP filter installed and available to you. Create a block with the php code
<?php
$ncount = db_query("SELECT COUNT(nid) FROM {node} WHERE status=%d", 1);
$ccount = db_query("SELECT COUNT(cid) FROM {comments} WHERE status=%d", 1);
print "Nodes: ".$ncount;
print "Comments: ".$ccount;
?>
One option is to use a View with the block display type. Views Calc can do the summing for you (http://drupal.org/project/views_calc).
Honestly, I think you will find it easier and possibly more performant to create a Statistics content type with CCK integer fields to store the initial values for the amount of each piece of information you need. Then configure the Rules module to increment/decrement the fields when you add or remove content/comments.
A third option I have not personally explored is the Statistics Pro module (http://drupal.org/project/statspro), which says it is Views-compatible.
Use Views GroupBy module ( http://drupal.org/project/views_groupby ). You can specify the filters (e.g. you want to count nodes of particular type only) and so on. It will count the nodes for you.
If your view type is comment then in a similar count can be done on comments.

After join, cannot filter by attribute qty - getting products from inventory that are in stock

You have been so helpful in the past that I keep coming back searching for help and learning.
This time I am trying to get all products that have a quantity greater than 1 and that are in stock (is_in_stock = 1)
$products = Mage::getModel('catalog/product')->getCollection();
//$products->addAttributeToSelect('*');
//SELECT `e`.*, `stock`.`qty` FROM `catalog_product_entity` AS `e` LEFT JOIN `cataloginventory_stock_item` AS `stock` ON stock.product_id = e.entity_id
$products->getSelect()->joinLeft(
array('stock'=>'cataloginventory_stock_item'),
'stock.product_id = e.entity_id',
array('stock.qty', 'stock.is_in_stock')
);
This returns qty and is_in_stock columns attached to the products table. You can test it as follows:
$products->getFirstItem()->getQty();
$products->getFirstItem()->getIsInStock();
The issue begins when I try to filter by qty and is_in_stock.
$products->addFieldToFilter(array(
array('Qty','gt'=>'0'),
array('Is_in_stock','eq'=>'1'),
));
This returns - Invalid attribute name never performing filtering. I am guessing it is trying search for e.qty but cannot find it.
So, I tried to filter differently:
$products->getSelect()->where("`qty` > 0");
$products->getSelect()->where("`is_in_stock` = 1");
This is not filtering as well even though, if you look at its sql query, (var_dump((string) $products->getSelect())), and run that query in phpMyAdmin, it works.
Alan Storm in his tutorial mentions that 'The database query will not be made until you attempt to access an item in the Collection'. So, I make the $products->getFirstItem() call but it still not executing the query or filtering in another words.
What am I doing wrong? Any ideas how to filter by attributes that are joined to the table?
Thank you again,
Margots
I would suggest that you try using $products->addAttributeToFilter... instead of $products->addFieldToFilter... - the addField method only works when the field is on the main table that you are querying (in this case catalog_product_entity). Because the inventory fields are in a joined table, you need to use addAttribute.
Hope this helps,
JD
After looking under the hood I learned that _selectAttributes instance field was not assigned in Mage_Eav_Model_Entity_Collection_Abstract class and that is why get exception. A solution usually would be what Jonathan Day suggested above - add addAttributeToFilter() method, however. It will return error since it cannot find such attribute for catalog/product. (qty and in_invetory are in cataloginventory_stock_item). I found two solutions to my problem both required going different direction:
One involved pursuing a way to query the Select statement that I had set for product collection(see above) but somehow it was not resetting the collection with new product. WhenI copied that Sql statment in phpMyAdmin, it worked, so how to query that statement from product collection:
$stmt = $products->getConnection('core_write')->query($products->getSelect()->__toString());
while($rows = $stmt->fetch(PDO::FETCH_ASSOC)){
echo "<br>Product Id ".$rows['entity_id'];
}
Instead of using catalog/product entity table I used the flat table - cataloginventory_stock_item to accomplish the same thing
$stockItem = new Mage_CatalogInventory_Model_Stock_Item();
$stockItems->addQtyFilter('>',0);
$stockItems->addFieldToFilter('is_in_stock',array('eq'=>'1'));
Now there is a collection of all products with qty > 0 and that are in stock.

Resources