i’m creating a woocommerce theme that have multiple product type: Mobile, Tablet, Camera,…
I created products types like this:
add_filter( 'product_type_selector', 'add_mobile_product_type' );
function add_mobile_product_type( $types ){
$types[ 'mobile' ] = __( 'Mobile' );
$types[ 'tablet' ] = __( 'Tablet' );
return $types;
}
add_action( 'plugins_loaded', 'create_mobile_product_type' );
function create_mobile_product_type(){
class WC_Product_Mobile extends WC_Product{
public function __construct( $product ) {
$this->product_type = 'mobile';
parent::__construct( $product );
}
}
class WC_Product_Tablet extends WC_Product{
public function __construct( $product ) {
$this->product_type = 'tablet';
parent::__construct( $product );
}
}
}
and i created some extra fields like this:
add_action( 'woocommerce_product_options_general_product_data', 'mobile_custom_fields' );
function mobile_custom_fields() {
global $woocommerce, $post;
$prefix = 'mobile_';
echo '<div class="options_group">';
woocommerce_wp_select(
array(
'id' => $prefix . 'sim',
'label' => __( 'Sim Count', 'faitell' ),
'options' => array(
'1' => __( '1 Sim', 'faitell' ),
'2' => __( '2 Sim', 'faitell' ),
'3' => __( '3 Sim', 'faitell' )
)
)
);
echo '</div>';
}
The problem is this fields will shown on all product types, how about show some fields for Mobile and some others for Tablet. is there any way?
I couldn’t find an easy way to do it in PHP, so I thought to add some Javascript to hide the field when needed.
Therefore your
mobile_custom_fields
function became:Note the
id="sim_count_select"
added to yourdiv
for easy targeting.Not the most elegant solution, but it should work.
add
show_if_{$product_type}
class alongside theoptions_group
class in the container above. For example, meta box to be showed only inmobile
product type addshow_if_mobile
.