get_sample_permalink()WP 2.5.0

Получает образец постоянной ссылки (пермалинка) записи.

Для работы функции во фронт-энде нужно подключить файл:

require_once ABSPATH . '/wp-admin/includes/post.php';
Хуки из функции

Возвращает

Массив. Массив из двух элементов: образец ссылки и ярлык (слаг) записи, который должен быть использован в образце:

Array(
	[0] => https://wp-kama.ru/%postname%.html
	[1] => customize-api
)

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

get_sample_permalink( $id, $title, $name );
$id(число/WP_Post) (обязательный)
ID или объект записи (поста), образец пермалинка которого нужно получить.
$title(строка)

Заголовок записи, который нужно использовать для создания ярлыка ссылки (post_name).

Для работы этого параметра в параметре $name нужно указать пустую строку. Если этого не сделать, то этот параметр нигде не будет использоваться, а просто будет передан в хук get_sample_permalink.

По умолчанию: null

$name(строка)
Ярлык записи, который перезапишет текущий ярлык (post_name). Влияет на работу параметра $title. Если указана не пустая строка, перебивает параметр $title (см. примеры).
По умолчанию: null

Примеры

0

#1 Демонстрация работы

require_once ABSPATH . '/wp-admin/includes/post.php';

$sample_permalink = get_sample_permalink( 10262 );
/*
Array (
	[0] => https://wp-kama.ru/%postname%.html
	[1] => customize-api
)
*/
0

#2 Использование всех параметров

$sample_permalink = get_sample_permalink( 10262, 'Мой заголовок' );
/*
	[0] => https://wp-kama.ru/%postname%.html
	[1] => customize-api
*/

$sample_permalink = get_sample_permalink( 10262, 'Мой заголовок', '' );
/*
	[0] => https://wp-kama.ru/%postname%.html
	[1] => moj-zagolovok
*/

$sample_permalink = get_sample_permalink( 10262, 'Мой заголовок', 'Если указать имя' );
/*
	[0] => https://wp-kama.ru/%postname%.html
	[1] => esli-ukazat-imya
*/

Список изменений

С версии 2.5.0 Введена.

Код get_sample_permalink() WP 6.4.3

function get_sample_permalink( $post, $title = null, $name = null ) {
	$post = get_post( $post );

	if ( ! $post ) {
		return array( '', '' );
	}

	$ptype = get_post_type_object( $post->post_type );

	$original_status = $post->post_status;
	$original_date   = $post->post_date;
	$original_name   = $post->post_name;
	$original_filter = $post->filter;

	// Hack: get_permalink() would return plain permalink for drafts, so we will fake that our post is published.
	if ( in_array( $post->post_status, array( 'draft', 'pending', 'future' ), true ) ) {
		$post->post_status = 'publish';
		$post->post_name   = sanitize_title( $post->post_name ? $post->post_name : $post->post_title, $post->ID );
	}

	/*
	 * If the user wants to set a new name -- override the current one.
	 * Note: if empty name is supplied -- use the title instead, see #6072.
	 */
	if ( ! is_null( $name ) ) {
		$post->post_name = sanitize_title( $name ? $name : $title, $post->ID );
	}

	$post->post_name = wp_unique_post_slug( $post->post_name, $post->ID, $post->post_status, $post->post_type, $post->post_parent );

	$post->filter = 'sample';

	$permalink = get_permalink( $post, true );

	// Replace custom post_type token with generic pagename token for ease of use.
	$permalink = str_replace( "%$post->post_type%", '%pagename%', $permalink );

	// Handle page hierarchy.
	if ( $ptype->hierarchical ) {
		$uri = get_page_uri( $post );
		if ( $uri ) {
			$uri = untrailingslashit( $uri );
			$uri = strrev( stristr( strrev( $uri ), '/' ) );
			$uri = untrailingslashit( $uri );
		}

		/** This filter is documented in wp-admin/edit-tag-form.php */
		$uri = apply_filters( 'editable_slug', $uri, $post );
		if ( ! empty( $uri ) ) {
			$uri .= '/';
		}
		$permalink = str_replace( '%pagename%', "{$uri}%pagename%", $permalink );
	}

	/** This filter is documented in wp-admin/edit-tag-form.php */
	$permalink         = array( $permalink, apply_filters( 'editable_slug', $post->post_name, $post ) );
	$post->post_status = $original_status;
	$post->post_date   = $original_date;
	$post->post_name   = $original_name;
	$post->filter      = $original_filter;

	/**
	 * Filters the sample permalink.
	 *
	 * @since 4.4.0
	 *
	 * @param array   $permalink {
	 *     Array containing the sample permalink with placeholder for the post name, and the post name.
	 *
	 *     @type string $0 The permalink with placeholder for the post name.
	 *     @type string $1 The post name.
	 * }
	 * @param int     $post_id Post ID.
	 * @param string  $title   Post title.
	 * @param string  $name    Post name (slug).
	 * @param WP_Post $post    Post object.
	 */
	return apply_filters( 'get_sample_permalink', $permalink, $post->ID, $title, $name, $post );
}