So I have been searching around looking for a way to incorporate this without installing another plugin that does way more than I need.
Lets say our product SKUs are structured in a way that provide the vendor number, then a dash (-), and then the product id. So our SKUs look like this 469-852369 (vendor-product). The vendor ID can be anywhere from 1 to 5 digits and the product ID can be anywhere from 1 to 10 digits. We want to be able to search for the product without having to add the dash (-). So for 469-852369 I want to be able to just type out 469852369 and the product appears.
I know there are a LOT of plugins out there that will do this but I don't want to add a plugin just to accomplish this one issue. Any help and guidance on how to accomplish this via PHP would help.
I am a novice so bare with me, Thank you
3 Answers
Answers 1
You can set your custom query to search result. while searching normally with "469852369" you can append "-" after 3 digits like "469-852369" and then pass it into WordPress query to get results.
function get_product_by_sku( $sku ) { global $wpdb; $sku = implode("-", str_split($sku, 3)); $product_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $sku ) ); if ( $product_id ) return new WC_Product( $product_id ); // YOUR CODE return null; }
Hope this will helpful for you somehow.
Thanks.
Answers 2
I think you could replace the SQL-query in Ahmed Ginani's answer with this one and get what you want:
SELECT post_id FROM $wpdb->postmeta WHERE (REPLACE(meta_value, '-', '')) = '%s' AND meta_key='_sku';
Answers 3
use the code:
function get_product_by_sku( $sku ) { global $wpdb; $product_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $sku ) ); if ( $product_id ) return new WC_Product( $product_id ); return null; }
0 comments:
Post a Comment