0

For WooCommerce I have a custom metabox that sets products to unavailable if ticked.

The code below removes the add to cart button if a product is set to unavailable:

// Remove add to cart button if product is set to unavailable
function bja_replace_add_to_cart_button($purchasable, $product) {
    $product_unavailable = get_post_meta($product->get_id(), '_product_unavailable', true);

    if ($product_unavailable === 'on') {
        $purchasable = false;       
    }
    
    return $purchasable;
}
add_filter('woocommerce_is_purchasable', 'bja_replace_add_to_cart_button', 10, 2);

In addition to removing the add to cart button, I'd like to add a line of text below the short description, to indicate the product is unavailable. For that I have the following code:

// Add text below short description
function bja_product_unavailable_text( $content ) {
    $content .= '<div class="bja_product_unavailable">This product is unavailable.</div>';
    return $content;
}
add_filter('woocommerce_short_description', 'bja_product_unavailable_text', 10, 2);

Both pieces of code work, but now I'd like to run the second piece only if the first one runs. What would be a good way of doing that?

1
  • put the 2nd filter inside that if statement
    – 1inMillion
    May 25 at 8:21

1 Answer 1

0

Following the suggestion by @1inmillion, I put the second filter inside the first IF statement, which works nicely.

This is the combined code:

// 1. Add text below short description
function bja_product_unavailable_text( $content ) {
    $content .= '<div class="bja_product_unavailable">This product is unavailable</div>';
    return $content;
}

// 2. Remove add to cart button if product is set to unavailable and add text below short description
function bja_replace_add_to_cart_button($purchasable, $product) {
    $product_unavailable = get_post_meta($product->get_id(), '_product_unavailable', true);

    if ($product_unavailable === 'on') {
        $purchasable = false;
        add_filter('woocommerce_short_description', 'bja_product_unavailable_text', 10, 2);
    }
    
    return $purchasable;
}
add_filter('woocommerce_is_purchasable', 'bja_replace_add_to_cart_button', 10, 2);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.