WooCommerce:如何有条件地更改产品链接?

时间:2020-11-03 10:39:54

标签: php wordpress woocommerce

WooCommerce中,我试图将售罄产品的默认产品链接格式https://domain-name.com/product/single-product-name/更改为以下格式:https://domain-name.com/product/single-product-name/#reviews

因此,如果产品售罄,我需要在产品链接中添加#reviews

通过functions.php,这会删除常规产品链接:

remove_action('woocommerce_before_shop_loop_item', 'woocommerce_template_loop_product_link_open');

但是我该如何解决这个问题

<a href="https://my-domain.com/product/the-product-title/">

进入这个了吗?

<a href="https://my-domain.com/product/the-product-title/#reviews">

页面上每种产品的相关HTML结构是:

<li class="product">
   <a href="https://my-domain.com/product/the-product-title/" class="woocommerce-LoopProduct-link woocommerce-loop-product__link">
     <img width="300" height="480" src="https://my-domain.com/wp-content/uploads/2020/10/the-product-title-300x480.jpg">
     <h2 class="woocommerce-loop-product__title">The Product Title</h2>
   </a>
</li

1 个答案:

答案 0 :(得分:2)

function append_reviews_to_sold_out_products( $post_link, $post ) {

    // If post is not a product, return default $post_link.
    if ( 'product' != $post->post_type ) {
        return $post_link;
    }
    
    // Get the product from the post ID
    $wcpf = new WC_Product_Factory();  
    $product = $wcpf->get_product($post->ID);

    // Check that it's managing stock, and that it has no stock
    if ( $product->managing_stock() && !$product->is_in_stock() ){
        // Append #reviews
        $post_link .= '#reviews';
    }
    
    // Return the link, appended or not.
    return $post_link;
    
}
add_filter( 'post_type_link', 'append_reviews_to_sold_out_products', 15, 4 );