【问题标题】:Redirect Out of Stock Product to the related category - woocommerce将缺货产品重定向到相关类别 - woocommerce
【发布时间】:2022-10-09 17:12:37
【问题描述】:

此任务与 WordPress woo 商务有关。 问:当产品缺货时,用户会使用插件自动重定向到产品的相关类别吗?

【问题讨论】:

    标签: wordpress woocommerce hook-woocommerce woocommerce-theming


    【解决方案1】:

    应该很简单,您可以使用get_stock_quantity() 检索产品库存。 get_the_terms() 检索产品类别,get_term_link() 检索术语 url。

    以下内容未经测试,但应该可以工作。

    <?php
    
    add_action( 'template_redirect', function () {
    
        if ( ! is_admin() && is_product() ) {
    
            global $product;
    
            $product_id = $product->get_id();
    
            if ( $product->get_stock_quantity() < 1 ) {
    
                $terms =  get_the_terms( $product_id, 'product_cat' );
                
                if ( ! empty( $terms ) ) {
    
                    $location = get_term_link( $terms[0]->slug );
    
                    wp_safe_redirect( $location, 302 );
    
                };
    
            };
    
        };
    
    } );
    

    【讨论】:

    • 您正在使用 $post-&gt;ID 但 $post 在您的代码中未定义。 template_redirect 钩子应该用于重定向并避免标头已经发送,而不是'init'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-09
    • 2013-08-11
    相关资源
    最近更新 更多