How to change a field label based on the category selected?

Hi,

I’m trying to modify the label of a field in the new listing form based on the category selected. Specifically, I want to change the “Location” label to “Pick Up Location” for listings filed under “Pick-ups” category.

I’ve tried using filters, and I’m able to change the label with the following code:

add_filter(
    'hivepress/v1/models/listing/attributes',
    function( $attributes ) {
        if ( isset( $attributes['location'] ) ) {
            $attributes['location']['edit_field']['label'] = 'PICK UP LOCATION';
        }
        return $attributes;
    },
    1000
);

However, I’m having trouble figuring out how to get the selected category in order to conditionally change the label. I was able to achieve this using JavaScript, but I would prefer to keep the function on the backend if possible.

Could someone please provide a sample code snippet or guidance on how to get the selected category in this case?

Thank you in advance for any help or suggestions!

Thank you for waiting. Please try this PHP code snippet. Please change number 100 on the category ID where you want to change the Location field label

add_filter(
	'hivepress/v1/forms/listing_update',
	function($args, $form){
		
		// Get listing.
		$listing = $form->get_model();
		
		if(!$listing){
			return $args;
		}
		
		$category_ids = $listing->get_categories__id();
		
		if(!$category_ids){
			return $args;
		}
		
		if(in_array(100, $category_ids)){
			$args['fields']['location']['label'] = 'Custom location';
		}
		
		return $args;
	},
	1000,
	2
);
3 Likes

Amazing! This works perfectly for my use case, thanks Yevhen!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.