【问题标题】:Add custom class to links if product is out of stock in WooCommerce如果 WooCommerce 中的产品缺货,则将自定义类添加到链接
【发布时间】:2018-02-03 20:45:55
【问题描述】:

在 WooCommerce 中,如果产品缺货,您是否知道向<a> html 元素(产品链接)添加类的方法?

基本上,我在一个页面上有产品链接,每个链接都指向一个特定的产品。如果该产品缺货,我正在尝试将“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 找到相应的项目(而不是使用通常的 slug URL)。

【问题讨论】:

    标签: php wordpress woocommerce shortcode product


    【解决方案1】:

    最简单的方法应该是为 html &lt;a&gt; 标签构建自定义函数短代码,其中包含产品链接和“缺货”时的附加类:

    这是功能代码:

    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。


    USAGE 示例 (针对您的情况)

    注意:我对 SVG 文件和 html 格式绝对不熟悉,所以我希望它能与 &lt;svg&gt;&lt;path&gt;&lt;/path&gt;&lt;/svg&gt; 一起使用。

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

    【讨论】:

    • 由于某种原因,当添加该功能时,它现在给我一个 HTTP ERROR 500。
    • 似乎是由于return = 。删除 = 似乎使它工作。在我将此标记为正确之前,您能告诉我prod_category 的作用,以及您选择它的原因吗?
    • prod_category 是干什么用的?
    • @Garconis 也更正/更新了……你应该用svg_product_link 替换它……对不起,谢谢
    • 关于使这些“添加到购物车”链接成为 ajax 的任何提示?所以当点击时,它只是添加它,没有任何重定向?
    猜你喜欢
    • 2023-03-23
    • 2022-08-03
    • 1970-01-01
    • 1970-01-01
    • 2022-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    相关资源
    最近更新 更多