WordPress как на ладони
rgbcode is looking for WordPress developers. Очень Удобный и Быстрый Хостинг для сайтов на WordPress. Пользуюсь сам и вам рекомендую!

get_the_content()WP 0.71

Получает контент текущей записи (поста). Используется внутри Цикла WordPress.

Когда функция используется на страницах архивов (не отдельная страница записи) и если в контенте используется тег-разделитель <!--more-->, то эта функция выведет не весь контент, а только текст до тега <!--more--> с последующей ссылкой "читать дальше" (текст ссылки можно изменить через параметр $more_link_text).

Не фильтрует контент, как это делает the_content(). Поэтому, если нужно получить результат с применением к контенту всех хуков the_content, используйте конструкцию:

$content = apply_filters( 'the_content', get_the_content() );
Основа для: get_the_content_feed(), the_content()
1 раз — 0.005081 сек (очень медленно) | 50000 раз — 3.32 сек (быстро) | PHP 7.2.5, WP 4.9.6
Хуки из функции

Возвращает

Строку.

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

get_the_content( $more_link_text, $strip_teaser, $post );
$more_link_text(строка)
Текст ссылки для места обрыва статьи (читать далее).
По умолчанию: null
$strip_teaser(логический)

Под словом teaser понимается привлекающий текст до тега more. strip_teaser - значит удалить этот текст. Т.е., если установить параметр в true, то контент до тега <!--more--> на is_single() странице будет удален.

По умолчанию параметр отключен. Его также можно включить, указав в любом месте текста записи <!--noteaser--> (принято указывать сразу после тега <!--more-->).
По умолчанию: null

$post(WP_Post/Объект/число) (с версии 5.2)
Запись (пост), контент которой нужно получить.
По умолчанию: null

Примеры

1

#1 Выведем контент поста, только если он не пустой

$the_content = apply_filters( 'the_content', get_the_content() );
if ( ! empty( $the_content ) ) {
	echo $the_content;
}

Для отдельного поста с ID 12:

$post = get_post( 12 ); // specific post
$the_content = apply_filters( 'the_content', $post->post_content );
if ( ! empty( $the_content ) ) {
	echo $the_content;
}
0

#2 Получим контент поста

Имейте ввиду, что эта функция не возвращает то же самое, что отображает the_content(). Чтобы вывести такой же контент, его нужно пропустить через хук the_content():

$content = apply_filters( 'the_content', get_the_content() );

echo $content;

Заметки

  • Global. int. $page Page number of a single post/page.
  • Global. int. $more Boolean indicator for whether single post/page is being viewed.
  • Global. true|false. $preview Whether post/page is in preview mode.
  • Global. Массив. $pages Array of all pages in post/page. Each array element contains part of the content separated by the <!--nextpage--> tag.
  • Global. int. $multipage Boolean indicator for whether multiple pages are in play.

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

С версии 0.71 Введена.
С версии 5.2.0 Added the $post parameter.

Код get_the_content() WP 6.4.3

function get_the_content( $more_link_text = null, $strip_teaser = false, $post = null ) {
	global $page, $more, $preview, $pages, $multipage;

	$_post = get_post( $post );

	if ( ! ( $_post instanceof WP_Post ) ) {
		return '';
	}

	/*
	 * Use the globals if the $post parameter was not specified,
	 * but only after they have been set up in setup_postdata().
	 */
	if ( null === $post && did_action( 'the_post' ) ) {
		$elements = compact( 'page', 'more', 'preview', 'pages', 'multipage' );
	} else {
		$elements = generate_postdata( $_post );
	}

	if ( null === $more_link_text ) {
		$more_link_text = sprintf(
			'<span aria-label="%1$s">%2$s</span>',
			sprintf(
				/* translators: %s: Post title. */
				__( 'Continue reading %s' ),
				the_title_attribute(
					array(
						'echo' => false,
						'post' => $_post,
					)
				)
			),
			__( '(more&hellip;)' )
		);
	}

	$output     = '';
	$has_teaser = false;

	// If post password required and it doesn't match the cookie.
	if ( post_password_required( $_post ) ) {
		return get_the_password_form( $_post );
	}

	// If the requested page doesn't exist.
	if ( $elements['page'] > count( $elements['pages'] ) ) {
		// Give them the highest numbered page that DOES exist.
		$elements['page'] = count( $elements['pages'] );
	}

	$page_no = $elements['page'];
	$content = $elements['pages'][ $page_no - 1 ];
	if ( preg_match( '/<!--more(.*?)?-->/', $content, $matches ) ) {
		if ( has_block( 'more', $content ) ) {
			// Remove the core/more block delimiters. They will be left over after $content is split up.
			$content = preg_replace( '/<!-- \/?wp:more(.*?) -->/', '', $content );
		}

		$content = explode( $matches[0], $content, 2 );

		if ( ! empty( $matches[1] ) && ! empty( $more_link_text ) ) {
			$more_link_text = strip_tags( wp_kses_no_null( trim( $matches[1] ) ) );
		}

		$has_teaser = true;
	} else {
		$content = array( $content );
	}

	if ( str_contains( $_post->post_content, '<!--noteaser-->' ) && ( ! $elements['multipage'] || 1 == $elements['page'] ) ) {
		$strip_teaser = true;
	}

	$teaser = $content[0];

	if ( $elements['more'] && $strip_teaser && $has_teaser ) {
		$teaser = '';
	}

	$output .= $teaser;

	if ( count( $content ) > 1 ) {
		if ( $elements['more'] ) {
			$output .= '<span id="more-' . $_post->ID . '"></span>' . $content[1];
		} else {
			if ( ! empty( $more_link_text ) ) {

				/**
				 * Filters the Read More link text.
				 *
				 * @since 2.8.0
				 *
				 * @param string $more_link_element Read More link element.
				 * @param string $more_link_text    Read More text.
				 */
				$output .= apply_filters( 'the_content_more_link', ' <a href="' . get_permalink( $_post ) . "#more-{$_post->ID}\" class=\"more-link\">$more_link_text</a>", $more_link_text );
			}
			$output = force_balance_tags( $output );
		}
	}

	return $output;
}
3 комментария
    Войти