如果产品在 WooCommerce 中缺货,则将自定义 class 添加到链接

Add custom class to links if product is out of stock in WooCommerce

在 WooCommerce 中,您知道在产品缺货时将 class 添加到 <a> html 元素(产品 link)的方法吗?

基本上,我在一个页面上有 link 个产品,每个 link 都指向一个特定的产品。如果该产品缺货,我正在尝试将 "oos" class 添加到产品的 link。然后我可以为这些 link 设置不同的样式。

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

我正在创建 SVG 地图。每个 piece/path 将 link 到特定产品。如果 link 编辑到的产品缺货,则应添加 "oos" class(这样该作品就不再可见)。

我不反对使用某种简码,如果这有帮助的话。但是短代码需要能够包装每个独特的 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 找到相应的项目(而不是使用通常的 slug URL)。

最简单的方法应该是为 html <a> 标签构建一个自定义函数短代码,其中产品 link 和附加的 class 当它是 "out of stock":

这是函数代码:

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>