如果产品在WooCommerce中缺货,请将链接添加到链接

问题描述:

在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)。

最简单的方法应该是建立一个自定义函数简码与商品链接和附加类的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