【发布时间】:2016-03-09 18:57:57
【问题描述】:
我目前在购物车中有可用的产品 ID,我需要检索 slug。我该怎么做?
【问题讨论】:
标签: wordpress woocommerce
我目前在购物车中有可用的产品 ID,我需要检索 slug。我该怎么做?
【问题讨论】:
标签: wordpress woocommerce
您可以使用get_post
$product = get_post( 27 );
$slug = $product->post_name;
echo $slug;
【讨论】:
除了get_post,如果您已经有产品或需要它用于其他目的,您可以使用get_product
$_pf = new WC_Product_Factory();
$product = $_pf->get_product($product_id);
$slug = $product->get_slug();
【讨论】:
产品就是帖子。要从帖子 ID 中检索与 post_name 帖子字段对应的帖子 slug,可以使用 get_post_field() 函数。
$product_slug = get_post_field('post_name', $product_id);
【讨论】:
`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;
}
}
【讨论】: