bp_activity_action_parse_url()

AJAX endpoint for link preview URL parser.

Description

Source

File: bp-activity/bp-activity-functions.php

function bp_activity_action_parse_url() {
	require_once trailingslashit( buddypress()->plugin_dir . 'bp-activity/vendors' ) . '/website-parser/website_parser.php';

	// curling
	$json_data = array();
	if ( class_exists( 'WebsiteParser' ) ) {

		$url    = $_POST['url'];

		if ( strpos( $url, 'youtube' ) > 0 || strpos( $url, 'youtu' ) > 0 || strpos( $url, 'vimeo' ) > 0 ) {

			// Fetch the oembed code for URL.
			$embed_code = wp_oembed_get( $url );

			$json_data['title']       = ' ';
			$json_data['description'] = $embed_code;
			$json_data['images']      = '';
			$json_data['error']       = '';

			wp_send_json( $json_data );
		}

		$parser = new WebsiteParser( $url );
		$body   = wp_remote_get( $url );

		if ( ! is_wp_error( $body ) && isset( $body['body'] ) ) {

			$title       = '';
			$description = '';
			$images      = array();

			$parser->content = $body['body'];

			$meta_tags = $parser->getMetaTags( false );

			if ( is_array( $meta_tags ) && ! empty( $meta_tags ) ) {
				foreach ( $meta_tags as $tag ) {
					if ( is_array( $tag ) && ! empty( $tag ) ) {
						if ( $tag[0] == 'og:title' ) {
							$title = $tag[1];
						}
						if ( $tag[0] == 'og:description' ) {
							$description = html_entity_decode( $tag[1], ENT_QUOTES, "utf-8" );
						} elseif ( strtolower( $tag[0] ) == 'description' && $description == '' ) {
							$description = html_entity_decode( $tag[1], ENT_QUOTES, "utf-8" );
						}
						if ( $tag[0] == 'og:image' ) {
							$images[] = $tag[1];
						}
					}
				}
			}
			if ( $title == '' ) {
				$title = $parser->getTitle( false );
			}
			if ( empty( $images ) ) {
				$images = $parser->getImageSources( false );
			}
			// Generate Image URL Previews
			if ( empty( $images ) ) {
				$content_type = wp_remote_retrieve_header( $body, 'content-type' );
				if ( false !== strpos( $content_type, 'image' ) ) {
					$images = array( $url );
				}
			}

			$json_data['title']       = $title;
			$json_data['description'] = $description;
			$json_data['images']      = $images;
			$json_data['error']       = '';
		} else {
			$json_data['error'] = 'Sorry! preview is not available right now. Please try again later.';
		}
	} else {
		$json_data['error'] = 'Sorry! preview is not available right now. Please try again later.';
	}

	wp_send_json( $json_data );
}

Changelog

Changelog
Version Description
BuddyBoss 1.0.0 Introduced.

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.