Inventory_Presser_Google_Maps_Widget_V3::widget( array $args, array $instance )

widget

Description Description

Outputs the widget front-end HTML


Top ↑

Parameters Parameters

$args

(array) (Required)

$instance

(array) (Required)


Top ↑

Return Return

(void)


Top ↑

Source Source

File: includes/widget/class-widget-google-maps-v3.php

	public function widget( $args, $instance ) {
		// If there is no API key, we're not showing anything
		if ( empty( $instance['api_key'] ) ) {
			return;
		}

		// Turn an array of location term slugs into an array of address data
		$popups         = array();
		$location_terms = get_terms(
			array(
				'hide_empty' => false,
				'slug'       => $instance['location_slugs'],
				'taxonomy'   => 'location',
			)
		);
		for ( $t = 0; $t < sizeof( $location_terms ); $t++ ) {
			$popup = new stdClass();
			/**
			 * Store the widget ID in case there are two instances of this
			 * widget on the same page.
			 */
			$popup->widget_id = $args['widget_id'] ?? 0;
			// Location title/dealership name
			$popup->name = $location_terms[ $t ]->name;
			// Address
			$popup->address = str_replace( "\r", '', str_replace( PHP_EOL, '<br />', $location_terms[ $t ]->description ) );
			// Get the latitude and longitude coordinates for this address
			$location = INVP::fetch_latitude_and_longitude( $location_terms[ $t ]->term_id );
			if ( false !== $location ) {
				$popup->coords      = new stdClass();
				$popup->coords->lat = $location->lat;
				$popup->coords->lon = $location->lon;
			}

			$meta         = get_term_meta( $location_terms[ $t ]->term_id );
			$popup->city  = $meta['address_city'][0] ?? '';
			$popup->state = $meta['address_state'][0] ?? '';
			$popup->zip   = $meta['address_zip'][0] ?? '';

			$popups[] = $popup;
		}

		// Enqueue JavaScript
		wp_enqueue_script(
			self::ID_BASE . '_goog',
			'https://maps.googleapis.com/maps/api/js?key=' . $instance['api_key']
		);
		$min = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';
		wp_enqueue_script(
			self::ID_BASE,
			plugins_url( "js/widget-google-maps-v3{$min}.js", INVP_PLUGIN_FILE_PATH ),
			array( self::ID_BASE . '_goog' )
		);
		wp_add_inline_script(
			self::ID_BASE,
			'const ' . self::ID_BASE . ' = ' . wp_json_encode(
				array(
					'locations' => $popups,
				)
			),
			'before'
		);

		// before and after widget arguments are defined by themes
		echo $args['before_widget'];

		$title = apply_filters( 'widget_title', $instance['title'] );
		if ( ! empty( $title ) ) {
			echo $args['before_title'] . $title . $args['after_title'];
		}

		echo '<div id="map_canvas" style="min-height: 175px;"></div>' . $args['after_widget'];
	}