Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WooCommerce - get product by title?

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.

like image 742
Seb G Avatar asked Nov 02 '25 20:11

Seb G


1 Answers

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')
}
like image 101
Prafulla Kumar Sahu Avatar answered Nov 04 '25 11:11

Prafulla Kumar Sahu