I currently have the product id available in the cart and I need to retrieve the slug. How can I do this?
Asked
Active
Viewed 2.0k times
4 Answers
4
Alternatively to get_post
, you can use get_product
if you already have a product or need it for other purpose
$_pf = new WC_Product_Factory();
$product = $_pf->get_product($product_id);
$slug = $product->get_slug();

pajouk
- 115
- 8
-
Can you link the documentation for this as well? – Pratik K. Mar 10 '23 at 16:48
4
A product is a post. To retrieve the post slug, that correspond to post_name
post field, from the post ID, the get_post_field() function can be used.
$product_slug = get_post_field('post_name', $product_id);

Yurié
- 2,148
- 3
- 23
- 40
0
`Hi, in my case I did it as below: I needed to customize add to cart button entirely on shop page and category page. so I used $product object for this purpose. I needed product id, slug and name, so it did it. hope this will help you as well on cart page.`
add_filter( 'woocommerce_loop_add_to_cart_link', 'ij_replace_add_to_cart_button', 10, 2 );
function ij_replace_add_to_cart_button( $button, $product ) {
$productid = $product->id;
$productslug = $product->slug;
$productname = $product->name;
if (is_product_category() || is_shop()) {
$button_text = __("More Info", "woocommerce");
$button_link = $product->get_permalink();
$button = '<a href="'. $button_link .'" data-quantity="1" class="button product_type_simple add_to_cart_button ajax_add_to_cart" data-product_id="'. $productid.'" data-product_sku="" aria-label="Add “'.$productname.'” to your cart" rel="nofollow" data-productslug="'. $productslug.'" >' . $button_text . ' </a>';
return $button;
}
}

Imran Javed
- 1
- 2