In WooCommerce
, I’m trying to change the default product link format https://domain-name.com/product/single-product-name/
for sold out products to the following format: https://domain-name.com/product/single-product-name/#reviews
.
So I need to add #reviews
to the product link, if the product is sold out.
Via functions.php
, this removes the regular product link:
remove_action('woocommerce_before_shop_loop_item', 'woocommerce_template_loop_product_link_open');
But how can I turn this:
<a href="https://my-domain.com/product/the-product-title/">
into this?
<a href="https://my-domain.com/product/the-product-title/#reviews">
The relevant HTML
structure for each product on the page is:
<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
Advertisement
Answer
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 );