Update listings attributes when vendor attribute updated

Hello,
I am trying to create a function that will update all the listings attributes whenever their parent vendor attribute is updated.

Any snippet with a hook could do that?
Thanks a lot !

Please clarify whether it should update listing attributes with a new value or how it should work?

Hi yevhen,
For exemple, Bob is a vendor, it has 2 properties: Bob’s house A and B.
Bob has an attribute “Dogs accepted”.
The property listings have the same attribute “Dogs accepted”
When Bob’s attribute “Dogs accepted” is changed to true, I want the property listings A and B’s attributes “Dogs accepted” to change to true.

Thanks for the details, there’s no such feature yet but we have it on the roadmap, for example this will allow syncing the vendor Location field with the listing Locations (e.g. if the vendor is a person offering services at the same location).

Do you have a snippet even partial for me to try to implement that?

Please try this one, replace “one, two, three” with the field names you want to keep in sync with the vendor fields:

add_action(
	'hivepress/v1/models/vendor/update',
	function( $vendor_id, $vendor ) {

		// Check status.
		if ( $vendor->get_status() !== 'publish' ) {
			return;
		}

		// Set attributes.
		$attributes = array_flip( [ 'one', 'two', 'three' ] );

		// Get values.
		$values = array_intersect_key( $vendor->serialize(), $attributes );

		// Get listings.
		$listings = HivePress\Models\Listing::query()->filter(
			[
				'status__in' => [ 'draft', 'pending', 'publish' ],
				'vendor'     => $vendor->get_id(),
			]
		)->get();

		// Update listings.
		foreach ( $listings as $listing ) {
			if ( array_intersect_key( $listing->serialize(), $attributes ) !== $values ) {
				$listing->fill( $values )->save( array_keys( $values ) );
			}
		}
	},
	10,
	2
);

add_action(
	'hivepress/v1/models/listing/update',
	function( $listing_id, $listing ) {

		// Get vendor.
		$vendor = $listing->get_vendor();

		if ( ! $vendor || $vendor->get_status() !== 'publish' ) {
			return;
		}

		// Get attributes.
		$attributes = array_flip( [ 'one', 'two', 'three' ] );

		// Get values.
		$values = array_intersect_key( $vendor->serialize(), $attributes );

		// Update listing.
		if ( array_intersect_key( $listing->serialize(), $attributes ) !== $values ) {
			$listing->fill( $values )->save( array_keys( $values ) );
		}
	},
	10,
	2
);

Thank you very much for your help :slight_smile:

1 Like

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