MaltaCode
MaltaCode

Reputation: 70

Acf Combine fields into new fields excluding a category of products

I have used the code described in this post: Wordpress/ACF merging multiple fields value to one

// This function runs after your post is saved function my_acf_save_post( $post_id ) {

// Get new value of field 1
$value1 = get_field( 'field1', $post_id );

// Get new value of field 2 
$value2 = get_field( 'field2', $post_id );

// Merged values with ; on the end
$merge = $value1.' ('.$value2.')';

// Update field 3 with the new value which should be
// value1 value2;
update_field( 'field3', $merge, $post_id ); } add_action('acf/save_post', 'my_acf_save_post', 20);

But I would like to extend the code to only include $value2 if the product is NOT in a category, for example product category "Oils". I am not a PHP developer, could anyone help me with this?

Upvotes: 0

Views: 211

Answers (1)

Bhautik
Bhautik

Reputation: 11282

You can use has_term to check whether the product is in a category or not. try the below code.

// This function runs after your post is saved
function my_acf_save_post( $post_id ) {

    // Get the new value of field 1
    $value1 = get_field( 'field1', $post_id );

    // do something if product is not in Oils category
    if( !has_term( 'Oils', 'product_cat', $post_id ) ) {
        
        // Get new value of field 2 
        $value2 = get_field( 'field2', $post_id );
        
        // Merged values with ; on the end
        $merge = implode( " ",$value1 ).' '.implode( " ",$value2 );

    }else{

        // Merged values with; on the end
        $merge = implode( " ",$value1 );

    }

    // Update field 3 with the new value which should be
    // value1 value2;
    update_field( 'field3', $merge, $post_id );
}
add_action( 'acf/save_post', 'my_acf_save_post', 20 );

Upvotes: 1

Related Questions