Your problem is that get_page_by_path()
returns a WP_Post
object, not a WC_Product
object. You need a WC_Product
object, because that’s the object that contains the product_type
property. You can get a WC_Product
from a WP_Post
via the wc_get_product()
function:
$post_obj = get_page_by_path( $slug, OBJECT, 'product' ); // this code help me to get product detials by slug
$product_obj = wc_get_product( $page_obj );
Your code still won’t work though, because the woocommerce_simple_add_to_cart
hook relies on the global $product
variable, which won’t be set to the product you’re querying here. You could set it yourself but I’m not sure of the side effects of that. The safest way in my view would be to use the [add_to_cart]
shortcode:
if(!empty($tracks[ $k ][ 'buy_link_a' ])){
list($hash, $slug) = explode("product/",$tracks[ $k ][ 'buy_link_a' ]);
$post_obj = get_page_by_path( $slug, OBJECT, 'product' ); // this code help me to get product detials by slug
$product_obj = wc_get_product( $page_obj );
echo do_shortcode( '[add_to_cart id="' . $product_obj->get_id() . '" show_price="false"]' );
}
If you just want the URL, use the [add_to_cart_url]
shortcode:
echo do_shortcode( '[add_to_cart_url id="' . $product_obj->get_id() . '"]' );
Also note that I used the get_type()
method instead of the product_type
property, since that property has been deprecated in favour of the method.