BP_REST_Media_Endpoint::bbp_media_update_rest_field_callback( object $object, object $value )

The function to use to update the medias’s value of the topic REST Field.

Description

Parameters

$object

(object) (Required) Value for the schema.

$value

(object) (Required) The value of the REST Field to save.

Return

(object)

Source

File: bp-media/classes/class-bp-rest-media-endpoint.php

	protected function bbp_media_update_rest_field_callback( $object, $value ) {

		$medias = wp_parse_id_list( $object );
		if ( empty( $medias ) ) {
			$value->bbp_media = null;
			return $value;
		}

		$p_id = $value->ID;

		// save activity id if it is saved in forums and enabled in platform settings.
		$main_activity_id = get_post_meta( $p_id, '_bbp_activity_id', true );

		// Get current forum ID.
		if ( 'reply' === $value->post_type ) {
			$forum_id = bbp_get_reply_forum_id( $p_id );
		} else {
			$forum_id = bbp_get_topic_forum_id( $p_id );
		}

		$group_ids = bbp_get_forum_group_ids( $forum_id );
		$group_id  = ( ! empty( $group_ids ) ? current( $group_ids ) : 0 );

		// fetch currently uploaded media ids.
		$existing_media                = array();
		$existing_media_ids            = get_post_meta( $p_id, 'bp_media_ids', true );
		$existing_media_attachment_ids = array();
		if ( ! empty( $existing_media_ids ) ) {
			$existing_media_ids = explode( ',', $existing_media_ids );

			foreach ( $existing_media_ids as $existing_media_id ) {
				$existing_media[ $existing_media_id ] = new BP_Media( $existing_media_id );

				if ( ! empty( $existing_media[ $existing_media_id ]->attachment_id ) ) {
					$existing_media_attachment_ids[] = $existing_media[ $existing_media_id ]->attachment_id;
				}
			}
		}

		$args = array(
			'upload_ids'  => $medias,
			'privacy'     => 'public',
			'activity_id' => $main_activity_id,
		);

		if ( ! empty( $group_id ) ) {
			$args['group_id'] = $group_id;
			$args['privacy']  = 'grouponly';
		}

		$medias_ids = $this->bp_rest_create_media( $args );

		if ( is_wp_error( $medias_ids ) ) {
			return;
		}

		$medias_ids = implode( ',', $medias_ids );

		// Save all attachment ids in forums post meta.
		update_post_meta( $p_id, 'bp_media_ids', $medias_ids );

		// delete medias which were not saved or removed from form.
		if ( ! empty( $existing_media_ids ) ) {
			foreach ( $existing_media_ids as $media_id ) {
				bp_media_delete( array( 'id' => $media_id ) );
			}
		}
	}

Questions?

We're always happy to help with code or other questions you might have! Search our developer docs, contact support, or connect with our sales team.