got stuck in WooCommerce & WordPress ( both latest versions ) with a little piece of code.
// What i want?
Some very similar option like “upselling” & cross-selling. If any customer want buy a product, like a stamp or something else should be able to choose some the correct hangtags who fits to the first product – like a stamp!
So far so good, figured it out with some lines of code, a new tab and an input_textfield. But typing in all these product_ID’s isn’t fun. With wc-product-search it should be easy and done in seconds. Grinding at least for more than 4 hours, but can’t get it working properly! It works so far but doesn’t update the meta if it got changed.
Is there any pro out there, who can provide some help?
/**
* Add a custom product tab.
*/
function matching_products_tab( $tabs) {
$tabs['matching_products'] = array(
'label' => __( 'Matching Products', 'eva' ),
'target' => 'matching_products',
'class' => array( 'show_if_simple', 'show_if_variable' ),
);
return $tabs;
}
add_filter( 'woocommerce_product_data_tabs', 'matching_products_tab' );
/**
* Contents of matching products tab
*/
function matching_product_tab_content() {
global $post, $woocommerce;
?><div id="matching_products" class="panel woocommerce_options_panel">
<div class="options_group">
<p class="form-field product_field_type">
<label for="product_field_type"><?php _e( 'Product Select', 'woocommerce' ); ?></label>
<select class="wc-product-search" multiple="multiple" style="width: 50%;" id="product_field_type" name="product_field_type[]" data-placeholder="<?php esc_attr_e( 'Search for a product…', 'woocommerce' ); ?>" data-action="woocommerce_json_search_products_and_variations" data-exclude="<?php echo intval( $post->ID ); ?>">
<?php
$product_field_type_ids = get_post_meta( $post->ID, '_product_field_type_ids', true );
$product_ids = ! empty( $product_field_type_ids ) ? array_map( 'absint', $product_field_type_ids ) : null;
if ( $product_ids ) {
foreach ( $product_ids as $product_id ) {
$product = get_product( $product_id );
$product_name = woocommerce_get_formatted_product_name( $product );
echo '<option value="' . esc_attr( $product_id ) . '" selected="selected">' . esc_html( $product_name ) . '</option>';
}
}
?>
</select>
</p>
</div>
</div><?php
}
add_action( 'woocommerce_product_data_panels', 'matching_product_tab_content' );
/**
* Save meta
*/
function save_matching_product_tab_content( $post_id ) {
$product_field_type = $_POST['product_field_type'];
update_post_meta( $post_id, '_product_field_type_ids', $product_field_type );
}
add_action( 'woocommerce_process_product_meta_simple', 'save_matching_product_tab_content' );
add_action( 'woocommerce_process_product_meta_variable', 'save_matching_product_tab_content' );
Read more here: WooCommerce | update_post_meta doesn’t work