【问题标题】:Woocommerce: How do I get the product slug from the id?Woocommerce:如何从 id 获取产品信息?
【发布时间】:2016-03-09 18:57:57
【问题描述】:

我目前在购物车中有可用的产品 ID,我需要检索 slug。我该怎么做?

【问题讨论】:

    标签: wordpress woocommerce


    【解决方案1】:

    您可以使用get_post

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

    【讨论】:

      【解决方案2】:

      除了get_post,如果您已经有产品或需要它用于其他目的,您可以使用get_product

      $_pf = new WC_Product_Factory();  
      $product = $_pf->get_product($product_id);
      $slug = $product->get_slug();
      

      【讨论】:

        【解决方案3】:

        产品就是帖子。要从帖子 ID 中检索与 post_name 帖子字段对应的帖子 slug,可以使用 get_post_field() 函数。

        $product_slug = get_post_field('post_name', $product_id);
        

        【讨论】:

          【解决方案4】:
              `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;
          }
          }
           
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2016-04-25
            • 1970-01-01
            • 1970-01-01
            • 2015-01-03
            • 1970-01-01
            • 2014-07-04
            相关资源
            最近更新 更多