epicrato
epicrato

Reputation: 8428

Woocommerce: How do I get the product slug from the id?

I currently have the product id available in the cart and I need to retrieve the slug. How can I do this?

Upvotes: 4

Views: 22942

Answers (4)

Imran Javed
Imran Javed

Reputation: 1

    `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;
}
}
 

Upvotes: 0

Iurie
Iurie

Reputation: 2248

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);

Upvotes: 4

pajouk
pajouk

Reputation: 115

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();

Upvotes: 4

silver
silver

Reputation: 5331

You can use get_post

$product = get_post( 27 ); 
$slug = $product->post_name;
echo $slug;

Upvotes: 11

Related Questions