To make this as simple and as easy as possible, I'm trying to add this checkbox on the top row next to the product type selector where you would normally find Virtual
and Download
.
The idea is to have the checkbox there so that no matter the product type, it is always available.
This is what I've tried:
add_action( 'woocommerce_product_type_options', 'remove_related_products_checkbox' );
function remove_related_products_checkbox() {
woocommerce_wp_checkbox( array(
'id' => '_remove_related_products',
'class' => '',
'label' => 'Remove Related Products?'
) );
}
add_action( 'save_post_product', 'related_products_checkbox_save' );
function remove_related_products_checkbox_save( $product_id ) {
global $pagenow, $typenow;
if ( 'post.php' !== $pagenow || 'product' !== $typenow ) return;
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
if ( isset( $_POST['_remove_related_products'] ) ) {
update_post_meta( $product_id, '_remove_related_products', $_POST['_remove_related_products'] );
} else
delete_post_meta( $product_id, '_remove_related_products' );
}
add_action( 'woocommerce_after_single_product_summary', 'remove_related_products_checkbox_display', 1 );
function remove_related_products_checkbox_display() {
global $product;
if ( ! empty ( get_post_meta( $product->get_id(), '_remove_related_products', true ) ) ) {
remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_related_products', 20 );
}
}
But it doesn't work… Any advice please?
Your code is a bit outdated since WooCommerce 3 and there are some mistakes.
Try the following instead:
add_filter( 'product_type_options', 'hide_related_products_option' );
function hide_related_products_option( $fields ) {
$fields['hide_related'] = array(
'id' => '_hide_related',
'wrapper_class' => '',
'label' => __('Remove Related Products'),
'description' => __( 'Remove/Hide related products.', 'woocommerce' ),
'default' => 'no'
);
return $fields;
}
add_action( 'woocommerce_admin_process_product_object', 'hide_related_products_option_save' );
function hide_related_products_option_save( $product ) {
$product->update_meta_data( '_hide_related', isset( $_POST['_hide_related'] ) ? 'yes' : 'no' );
}
add_action( 'woocommerce_after_single_product_summary', 'remove_related_products_checkbox_display', 1 );
function remove_related_products_checkbox_display() {
global $product;
if ( $product->get_meta('_hide_related') === 'yes' ) {
remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_related_products', 20 );
}
}
Code goes in function.php file of your active child theme (active theme). Tested and works.
Related: Add checkbox to product type option in Woocommerce backend product edit pages