php - WooCommerce Get the product object from the product title -
i making code product object product title. reading product title notepad file , passing wordpress function.
below function in $pval
product title.
$productdetail_by_title = get_page_by_title($pval, object, 'product'); print_r($productdetail_by_title); exit;
product title this: 200x slopupovací pleťová rusk
but not able product object. if pass statically title this:
$productdetail_by_title = get_page_by_title("200x slopupovací pleťová rusk", object, 'product'); print_r($productdetail_by_title); exit;
then able product object. please help.
with get_page_by_title()
wordpress function, not wc_product
objet if it's working wp_post
object.
so here custom built function output wc_product object, if title matches 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 $post_table post_title '$post_title' , post_type 'product' "); // 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 active child theme (or theme) or in plugin file.
example usage:
// title set in variable $title = "200x slopupovací pleťová rusk"; // using our custom function instance of wc_product object $product_obj = get_wc_product_by_title( $title ); // testing output print_r($product_obj);
this code tested on woocommerce 3+ , works.
Comments
Post a Comment