dimanche 24 février 2019

Change Add To Cart button on shop archives based on condition of custom admin checkbox

I have created a custom admin product checkbox and if this checkbox is active I would like to replace the 'Add To Cart' button for these products on any shop archive/category page to 'View Product' instead and the button should take the viewer to the product page.

Other shop items that do not have the checkbox active should behave normally and display the 'Add To Cart' button with its functionality preserved.

I have got the checkbox working on the admin end with no issues with the following code :

// Display Checkbox
add_action('woocommerce_product_options_general_product_data', 'product_custom_fields_add');
function product_custom_fields_add(){
    global $post;

    echo '<div class="product_custom_field">';

    // Custom Product Checkbox Field
    woocommerce_wp_checkbox( array(
        'id'        => '_no_addcart_product',
        'desc'      => __('show or hide add to cart', 'woocommerce'),
        'label'     => __('Hide Add To Cart', 'woocommerce'),
        'desc_tip'  => 'true'
    ));

    echo '</div>';
}

// Save Checkbox
add_action('woocommerce_process_product_meta', 'product_custom_fields_save');
function product_custom_fields_save($post_id){
    // Custom Product Text Field
    $no_addcart_product = isset( $_POST['_no_addcart_product'] ) ? 'yes' : 'no';
        update_post_meta($post_id, '_no_addcart_product', esc_attr( $no_addcart_product ));
}

I have come up with this code below to try and add the if condition based on the checkbox status.

add_filter( 'woocommerce_loop_add_to_cart_link', 'replacing_add_to_cart_button', 10, 2 );
function replacing_add_to_cart_button( $button, $product  ) {
   if (  $product->get_meta('_no_addcart_product') === 'yes' )
   $button_text = __("View product", "woocommerce");
   $button = '<a class="button" href="'. $product->get_permalink().'">' . $button_text.'</a>';
   return $button;
}

It works partially in changing the button text and the link for any product that has the checkbox active correctly. However the issue is that it also removes the text from all other shop items and leaves a blank button for any item that hasn't got the checkbox active (see image below). The links of these products are also changed to the product pages and not 'Add To Cart' as I would like them to remain.

Empty Buttons

I have read through a lot of threads that change the button globally for all products but haven't been able to find any conditional logic applied only to certain products that could help me figure this one out. So any help would be greatly appreciated. Many thanks in advance.

Aucun commentaire:

Enregistrer un commentaire