具有
get_page_by_title()
WordPress函数,您将无法获得
WC_Product
但是如果它起作用,你会得到
WP_Post
因此,这里有一个定制函数,如果标题与真实的产品标题匹配,它将输出WC_产品对象:
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] ) );
}
代码进入函数。活动子主题(或主题)或任何插件文件中的php文件。
示例用法:
// 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);
这段代码在WooCommerce 3+上进行了测试,效果良好。