функция since 3.0.0

wp_get_shortlink()

Проверено на WordPress 6.9, обновлено Источник: WordPress Developer Resources.

Сигнатура

wp_get_shortlink( int $id, string $context = 'post', bool $allow_slugs = true ): string

Описание

Эта функция существует для того, чтобы предоставить тег короткой ссылки, на который могут ориентироваться все темы и плагины.
Чтобы предоставить реальные короткие ссылки, плагин должен подключиться к соответствующему хуку. Встроенная поддержка коротких ссылок ограничивается предоставлением ссылок вида ?p= для записей. Плагины могут прервать выполнение этой функции через фильтр «pre_get_shortlink» или отфильтровать её вывод через фильтр «get_shortlink».

Оригинал (английский)

This function exists to provide a shortlink tag that all themes and plugins can target.
A plugin must hook in to provide the actual shortlinks. Default shortlink support is limited to providing ?p= style links for posts. Plugins can short-circuit this function via the ‘pre_get_shortlink’ filter or filter the output via the ‘get_shortlink’ filter.

Параметры

$id int необязательный
ID записи или сайта. Значение по умолчанию 0, что означает текущую запись или сайт.
$context string необязательный = 'post'
Является ли ID идентификатором 'site', 'post' или 'media'. Если 'post', учитывается post_type записи. Если 'query', для определения ID и контекста используется текущий запрос. Значение по умолчанию 'post'.
$allow_slugs bool необязательный = true
Разрешать ли слаги записей в короткой ссылке. Как и стоит ли это учитывать, решает сам плагин.

Возвращаемое значение

string

Исходный код

wp-includes/link-template.php:4153

function wp_get_shortlink( $id = 0, $context = 'post', $allow_slugs = true ) {
	/**
	 * Filters whether to preempt generating a shortlink for the given post.
	 *
	 * Returning a value other than false from the filter will short-circuit
	 * the shortlink generation process, returning that value instead.
	 *
	 * @since 3.0.0
	 *
	 * @param false|string $return      Short-circuit return value. Either false or a URL string.
	 * @param int          $id          Post ID, or 0 for the current post.
	 * @param string       $context     The context for the link. One of 'post' or 'query',
	 * @param bool         $allow_slugs Whether to allow post slugs in the shortlink.
	 */
	$shortlink = apply_filters( 'pre_get_shortlink', false, $id, $context, $allow_slugs );

	if ( false !== $shortlink ) {
		return $shortlink;
	}

	$post_id = 0;
	if ( 'query' === $context && is_singular() ) {
		$post_id = get_queried_object_id();
		$post    = get_post( $post_id );
	} elseif ( 'post' === $context ) {
		$post = get_post( $id );
		if ( ! empty( $post->ID ) ) {
			$post_id = $post->ID;
		}
	}

	$shortlink = '';

	// Return `?p=` link for all public post types.
	if ( ! empty( $post_id ) ) {
		$post_type = get_post_type_object( $post->post_type );

		if ( 'page' === $post->post_type
			&& 'page' === get_option( 'show_on_front' ) && (int) get_option( 'page_on_front' ) === $post->ID
		) {
			$shortlink = home_url( '/' );
		} elseif ( $post_type && $post_type->public ) {
			$shortlink = home_url( '?p=' . $post_id );
		}
	}

	/**
	 * Filters the shortlink for a post.
	 *
	 * @since 3.0.0
	 *
	 * @param string $shortlink   Shortlink URL.
	 * @param int    $id          Post ID, or 0 for the current post.
	 * @param string $context     The context for the link. One of 'post' or 'query',
	 * @param bool   $allow_slugs Whether to allow post slugs in the shortlink. Not used by default.
	 */
	return apply_filters( 'get_shortlink', $shortlink, $id, $context, $allow_slugs );
}

История изменений

ВерсияОписание
3.0.0 Introduced.

Что будем искать? Например,Продвижение

Этот сайт использует куки-файлы. Оставаясь на сайте, Вы соглашаетесь на их использование. Для получения дополнительной информации, пожалуйста, ознакомьтесь с политикой в отношении персональных данных.