2
votes

In WooCommerce, do you know of a way to add a class to a <a> html element (product link) if the product is out of stock?

Basically, I have product links on a page, and each link goes to a particular product. I am trying to add an "oos" class to the product's link, if that product is out of stock. Then I can style those links differently.

More info: https://jsfiddle.net/Garconis/qtvkxkga/

I am creating an SVG map. Each piece/path will link to a particular product. If the product that it's linked to is out of stock, it should then add the "oos" class (so that the piece is no longer visible).

I'm not opposed to using some sort of shortcode, if that will help things. But the shortcode would need to be able to wrap each of the unique SVG paths.

In stock:

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

Out of stock:

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

Note, in the URL, I can also use the product's ID if that helps PHP find the corresponding item (as opposed to using the usual slug URL).

1

1 Answers

1
votes

The simplest way should be to build a custom function shortcode for the html <a> tag with the product link and the additional class when it's "out of stock":

Here is that function code:

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' );
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested on WooCommerce 3+ and output the desired html.


USAGE Example (for your case):

Note: I am absolutely not familiar with SVG files and html format, so I hope that it will work with <svg><path></path></svg>.

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