Support

Account

Home Forums ACF PRO Add value to custom field when creating a product

Solved

Add value to custom field when creating a product

  • Hello,

    I’m using the rest api to add products to WooCommerce. The products have a custom field called affiliate_link (created with the acf plugin).

    If I manually enter a value into this field, I can display this in the get product response – it looks like: affiliate_link: ‘the new value’

    However, if I try to set the value dynamically. Nothing happens – it looks like: affiliate_link: null

    PHP:

    
    add_action('rest_api_init', 'rest_api_init_func');
    function rest_api_init_func(){
    	
        register_rest_field('product', 'affiliate_link',
            array(
    			'get_callback' => 'the_callback_func_get',
    			'update_callback' => 'the_callback_func_update',
                'schema' => null,
            )
        );
    }
    function the_callback_func_get($post) {
    	$id = $post['id'];
    	$brand_type = get_field('affiliate_link', $id );
    	
    		return $brand_type;
    
    }
    function the_callback_func_update($value, $post) {
    	$id = $post['id'];
    	update_field('group_5f48ff79c7e23',$value, $id );
    
    }
    

    JS:

     
    apiV3.post("products", {
            ...
            fields: {
                affiliate_link: <code>${itemA.affilLink}</code>,
            }
        })
    

    I’m using the JavaScript Rest API Library:
    https://www.npmjs.com/package/@woocommerce/woocommerce-rest-api

    Can anyone point me in the right direction on how to add a value to a custom field when creating a product?

  • You are using the field group key here

    
    update_field('group_5f48ff79c7e23',$value, $id );
    

    try using the field key which should look something like field_XXXXXXXX

  • Thanks for the response.

    However, I updated the update_field to:

    
    update_field('affiliate_link', $value ,$object->get_id());
    

    With WooCommerce, I had to use get_id().

    I can now programmatically set the custom field value.

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.