2017-08-25 125 views
2

在WooCommerce中,如果產品缺貨,您是否知道如何將類添加到<a> html元素(產品鏈接)?如果產品在WooCommerce中缺貨,請將鏈接添加到鏈接

基本上,我在一個頁面上有產品鏈接,並且每個鏈接都轉到特定的產品。如果產品缺貨,我正在嘗試在產品鏈接中添加「oos」類。然後,我可以對這些鏈接進行不同的設計

更多信息: https://jsfiddle.net/Garconis/qtvkxkga/

我創建的SVG地圖。每件作品/路徑將鏈接到特定的產品。如果它所鏈接的產品缺貨,則應該添加「oos」類(以便該部分不再可見)。

我不反對使用某種短代碼,如果這將有所幫助。但是短代碼需要能夠包裝每個獨特的SVG路徑。

庫存:

<svg> 
    <a href="https://example.com/?p=332"> 
     <path></path> 
    </a> 
</svg> 

缺貨:

<svg> 
    <a href="https://example.com/?p=332" class="oos"> 
     <path></path> 
    </a> 
</svg> 

注意,在URL中,我也可以使用該產品的ID,是否可以幫助PHP找到相應的項目(相對使用通常的slu URL URL)。

回答

1

最簡單的方法應該是建立一個自定義函數簡碼與商品鏈接和附加類的HTML <a>標籤時,它的「缺貨」:

下面是功能代碼:

if(!function_exists('custom_shortcode_svg_product_link')) { 

    function custom_shortcode_svg_product_link($atts, $content = null) { 

     // Shortcode Attributes 
     $atts = shortcode_atts(
      array(
       'id' => '', 
      ), 
      $atts, 'svg_product_link' 
     ); 

     $product_id = $atts['id']; 
     // Get an instance of the WC_Product object 
     $product = wc_get_product($product_id); 
     // Display the class "oos" when product is out of stock 
     $class = $product->is_in_stock() ? '"' : '" class="oos"'; 
     // The product link 
     $product_link = $product->get_permalink(); 

     // The output 
     return '<a href="'.$product_link.$class.'>'.$content.'</a>'; 
    } 
    add_shortcode('svg_product_link', 'custom_shortcode_svg_product_link'); 
} 

代碼會出現在您的活動子主題(或主題)的function.php文件中,也可能位於任何插件文件中。

在WooCommerce 3+上測試並輸出所需的html。


使用示例(你的情況)

注:我絕對不熟悉SVG文件和HTML格式的,所以我希望它會與<svg><path></path></svg>工作。

/* 
* @ id (the product ID argument) 
*/ 
<svg> 
    [svg_product_link id="332"] 
     <path></path> 
    [/svg_product_link] 
    </a> 
</svg> 
+0

由於某些原因,現在當它添加該函數時,它會給我一個HTTP ERROR 500。 – Garconis

+0

似乎是由於'return ='。刪除'='似乎使它工作。在我將其標記爲正確之前,您能告訴我什麼是prod_category嗎?爲什麼選擇這個? – Garconis

+0

什麼是'prod_category'? – Garconis

相關問題