Yoast\WP\SEO\Helpers

Image_Helper::get_attachment_by_url()publicYoast 1.0

Find an attachment ID for a given URL.

Метод класса: Image_Helper{}

Возвращает

int. The found attachment ID, or 0 if none was found.

Использование

$Image_Helper = new Image_Helper();
$Image_Helper->get_attachment_by_url( $url, $use_link_table );
$url(строка) (обязательный)
The URL to find the attachment for.
$use_link_table(true|false)
Whether the SEO Links table will be used to retrieve the id.
По умолчанию: true

Код Image_Helper::get_attachment_by_url() Yoast 22.7

public function get_attachment_by_url( $url, $use_link_table = true ) {
	// Don't try to do this for external URLs.
	$parsed_url = \wp_parse_url( $url );
	if ( $this->url_helper->get_link_type( $parsed_url ) === SEO_Links::TYPE_EXTERNAL ) {
		return 0;
	}

	/** The `wpseo_force_creating_and_using_attachment_indexables` filter is documented in indexable-link-builder.php */
	if ( ! $this->options_helper->get( 'disable-attachment' ) || \apply_filters( 'wpseo_force_creating_and_using_attachment_indexables', false ) ) {
		// Strip out the size part of an image URL.
		$url = \preg_replace( '/(.*)-\d+x\d+\.(jpeg|jpg|png|gif)$/', '$1.$2', $url );

		$indexable = $this->indexable_repository->find_by_permalink( $url );

		if ( $indexable && $indexable->object_type === 'post' && $indexable->object_sub_type === 'attachment' ) {
			return $indexable->object_id;
		}

		$post_id = WPSEO_Image_Utils::get_attachment_by_url( $url );

		if ( $post_id !== 0 ) {
			// Find the indexable, this triggers creating it so it can be found next time.
			$this->indexable_repository->find_by_id_and_type( $post_id, 'post' );
		}

		return $post_id;
	}

	if ( ! $use_link_table ) {
		return WPSEO_Image_Utils::get_attachment_by_url( $url );
	}
	$cache_key = 'attachment_seo_link_object_' . \md5( $url );

	$found = false;
	$link  = \wp_cache_get( $cache_key, 'yoast-seo-attachment-link', false, $found );

	if ( $found === false ) {
		$link = $this->seo_links_repository->find_one_by_url( $url );
		\wp_cache_set( $cache_key, $link, 'yoast-seo-attachment-link', \MINUTE_IN_SECONDS );
	}
	if ( ! \is_a( $link, SEO_Links::class ) ) {
		return WPSEO_Image_Utils::get_attachment_by_url( $url );
	}

	return $link->target_post_id;
}