Skip to content
Advertisement

Woocommerce show custom button in specific category

It’s possible to show this code only on a specific category ?

thank you!

add_action('woocommerce_single_product_summary','cmk_additional_button');
function cmk_additional_button() {
    echo '<button type="submit" class="button alt">Change me please</button>';
}

Advertisement

Answer

add_action( 'woocommerce_single_product_summary', 'cmk_additional_button' );
function cmk_additional_button() {
    global $product;

    if (
        count(
            array_intersect(
                allowed_categories(), // Allowed Categories.
                wc_get_product_cat_ids( $product->get_id() ) // Product category ids.
            ) // Check any match for allowed category.
        ) > 0 // Pass the condition if atleast one allowed category exists.
    ) {
        echo '<button type="submit" class="button alt">Change me please</button>';
    }
}

function allowed_categories() {
    return array( 18, 20 );
}
  1. The function cmk_additional_button do a conditional check whether the current product have allowed categories id.
  2. If it have then displays the button.
  3. Function allowed_categories is return an array of allowed category which is used to compare with the current single product’s categories.
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement