Reputation: 671
How can you get a product by it's name? I know you can do it by ID and SKU, but for my current situation I need to grab a product by its title. I've been looking it up and can't seem to find the function.
My function occurs on the single product page, but the product I need to get data from WILL NOT be the current product that the user is looking at. Instead it will have the same name as the current product, just ending with a different symbol. (the product the user will be looking at ends with "-r" and the one I need to search for ends with "-$$$")
So far in my Functions.php:
function fill_refurbished_addon_selectbox(){
//get id of current product
global $product;
$id= $product->get_id();
//get name of product
$currentName = get_the_title($id);
//remove -r, add -$$$ and store in var
$searchFor = substr($currentName, 0, -2) . "-$$$";
echo $searchFor;
//find $$$ product by title
$coreCharge = ***GET PRODUCT BY TITLE ($searchFOr)***;
//get price of $$$ product, store in var
//populate dropbox
}
add_action('woocommerce_before_add_to_cart_button', 'fill_refurbished_addon_selectbox', 20);
The reason is, I need to fill a select box with info from the -$$$ product.
Upvotes: 4
Views: 16186
Reputation: 692
The highest voted answer here uses a custom WP_Query
, and https://github.com/woocommerce/woocommerce/wiki/wc_get_products-and-WC_Product_Query explains that this is likely to break your code in future versions of WooCommerce as data moves towards custom tables for better performance. wc_get_products
provides a standard way of retrieving products that is safe to use and will not break due to database changes in future WooCommerce versions:
$products = wc_get_products( array(
'name' => $product_name
) );
if ( count( $products ) == 1 ) {
$product = $products[0];
} else {
// handle when 0 or more than 1 product uses that name
}
Upvotes: 0
Reputation: 9693
please try this
$product = get_page_by_title( 'Product Title', OBJECT, 'product' );
get_page_by_title retrieves a post given its title. If more than one post uses the same title, the post with the smallest ID will be returned.
syntax:- get_page_by_title( $page_title, $output, $post_type );
In wordpress 6.2 this function is deprecated
instead you can use it's definition with little bit of change
function get_page_by_title(string $name, string $post_type = "post") {
$query = new WP_Query([
"post_type" => $post_type,
"name" => $name
]);
return $query->have_posts() ? reset($query->posts) : null;
}
now call get_page_by_title(<product_name>, 'product')
or if you want to make it WooCommerce specific, you can create a wrapper called
function get_product_by_title($productTitle) {
return get_page_by_title($productTitle, 'product')
}
Upvotes: 14