Create WooCommerce Product save product id to ACF field
Create WooCommerce Product save product id to ACF field
So currently I created a custom button on my custom post type "vault" that when clicked it will turn the info of that custom post type into a WooCommerce product. Once the WooCommerce product is created it should pass back the product ID and save it to a ACF field called woo_product_id. Currently it's not saving the product ID to that field but the product is being created.
Here is my code:
// Hook to save ACF field after custom post type is created or updated
function save_acf_field_to_custom_post_type($vault_id, $acf_field_value) {
// Check if it's the desired custom post type
if (get_post_type($vault_id) === 'vault') {
// Check if the ACF field value is provided
if ($acf_field_value !== null) {
// Update the post meta with the ACF field value
update_post_meta($vault_id, 'woo_product_id', $acf_field_value);
}
}
}
// Create Sell Button
function blz_add_sell_button_to_vault( $post ) {
// Checking its the correct post type
if ( get_post_type( $post ) == 'vault' ){
echo '<div class="email-buttons" style="padding-right:20px;"><input id="make-product" class="button-primary" name="make-product" type="submit" value="Move To Store" /></div>';
}
}
add_action('post_submitbox_minor_actions', 'blz_add_sell_button_to_vault', 10, 2 );
/**
* Create Product in WooCommerce
*
* @param integer $post_ID
* @param WP_Post $post
* @param boolean $update
* @return void
* */
function blz_check_if_send_email_button_pushed(int $post_ID, WP_Post $post, bool $update){
if ( key_exists( 'make-product', $_POST ) && $_POST['make-product'] == 'Move To Store'){
// Get Models Basic Info
$figureInfo = get_post($post_ID);
$figureName = $figureInfo->post_title;
$figurePrice = get_field('price');
$figurePhoto = get_post_thumbnail_id($post_ID);
$figureSlug = basename(get_permalink($post_ID));
$figurePhotos = array();
foreach (get_field('photo_gallery') as $images) {
array_push($figurePhotos, $images['ID']);
}
// Pass Figure info to WooCommerce
$product = new WC_Product_Simple();
$product->set_name($figureName); // product title
$product->set_slug($figureSlug);
$product->set_regular_price( $figurePrice ); // in current shop currency
$product->set_image_id( $figurePhoto );
$product->set_gallery_image_ids($figurePhotos);
$product->save();
save_acf_field_to_custom_post_type($figureInfo->ID, '123456');
}
}
add_action( 'save_vault_post', 'blz_check_if_send_email_button_pushed', 10, 3 );
Turbo Multi-language Translator
Make the better internet purchasing globaly
Turbosify SEO Speed Booster
5.0 (7)•Free plan available
Get better conversions by improving store loading speed
Installed
Turbo Multi-language Chat - AI Customer service in one hand