Search code examples
phpwordpresswoocommerceproductpage-title

WooCommerce Get the product object from the product title


I am making a code to get product object from product title. I am reading product title from my notepad file and passing it to Wordpress function.

Below is a function in which $pval is a product title.

 $productdetail_by_title = get_page_by_title($pval, OBJECT, 'product');
 print_r($productdetail_by_title);
 exit;

product title is something like this: 200x Slopupovací pleťová Rusk

But I am not able to get product object. If i pass statically this title like this:

$productdetail_by_title = get_page_by_title("200x Slopupovací pleťová Rusk", OBJECT, 'product');
print_r($productdetail_by_title);
exit;

Then I am able to get product object. Please help.


Solution

  • With get_page_by_title() WordPress function, you will not get the WC_Product objet but if it's working you will get the WP_Post object.

    So here is a custom built function that will output the WC_Product object, if the title matches with a real product title:

    function get_wc_product_by_title( $title ){
        global $wpdb;
    
        $post_title = strval($title);
    
        $post_table = $wpdb->prefix . "posts";
        $result = $wpdb->get_col("
            SELECT ID
            FROM $post_table
            WHERE post_title LIKE '$post_title'
            AND post_type LIKE 'product'
        ");
    
        // We exit if title doesn't match
        if( empty( $result[0] ) ) 
            return;
        else
            return wc_get_product( intval( $result[0] ) );
    }
    

    Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

    EXAMPLE USAGE:

    // Your title set in a variable
    $title = "200x Slopupovací pleťová Rusk";
    
    // Using our custom function to get an instance of the WC_Product object
    $product_obj = get_wc_product_by_title( $title );
    
    // Testing the output
    print_r($product_obj);
    

    This code is tested on WooCommerce 3+ and works.