the_contentхук-фильтрWP 0.71

Используется для фильтрации контента записи, после того как контент получен из базы данных, но до того как он будет выведет на экран.

Всегда обращайте внимание на то, чтобы передаваемая переменная $content была возвращена обратно после обработки, иначе пользователи увидят пустую страницу.

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

add_filter( 'the_content', 'filter_function_name_11' );
function filter_function_name_11( $content ) {
	// Фильтр...

	return $content;
}
$content(строка)
Строка, которую нужно отфильтровать и вернуть обратно.

Примеры

0

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

Для демонстрации работы фильтра, добавим в конец каждого текста поста надпись " Конец!":

add_filter('the_content', 'the_end');
function the_end( $text ){
	return $text . ' Конец!';
}
0

#2 Фильтр контента отдельной страницы

Этот пример можно использовать, для создания постоянной страницы контент которой будет генерироваться в зависимости от чего-либо, допустим переменной $_GET запроса (например для указанного автора ?the_author=crank):

add_filter( 'the_content', 'my_the_content_filter' );
function my_the_content_filter( $content ){
	// Если не страница debug ничего не делаем
	if( $GLOBALS['post']->post_name != 'debug' )
		return $content;

	// Выполняем действия
	// предполагается что в УРЛ указана переменная запроса the_author
	return "Это страница автора: ". $_GET['the_author'];
}
0

#3 Иконка поста

Этот пример добавит картинку перед постом (смотрите is_single()). Подразумевается, что картинки называется post_icon.png и находится в папке image в каталоге темы. Фильтр работает в пониженном приоритете 20 (обычно 10), это значит что он будет обработан позднее остальных.

add_filter( 'the_content', 'my_the_content_filter', 20 );
function my_the_content_filter( $content ){
	if ( is_single() )
		// Добавляем картинку в начало каждой страницы
		$content = sprintf(
			'<img class="post-icon" src="%s/images/post_icon.png" alt="Post icon" title=""/>%s',
			get_bloginfo( 'stylesheet_directory' ),
			$content
		);

	// Возвращаем контент.
	return $content;
}
0

#4 Миниатюра поста в начале

Этот пример показывает, как добавить миниатюру поста перед выводом контента. Миниатюра поста устанавливается при редактировании поста (эта функция должна быть включена, смотрите add_theme_support()). Миниатюра будет добавлена только к постам (записям типа post):

add_filter( 'the_content', 'featured_image_before_content' );
function featured_image_before_content( $content ) {
	if ( is_singular('post') && has_post_thumbnail()) {
		$thumbnail = get_the_post_thumbnail();

		$content = $thumbnail . $content;
	}

	return $content;
}
0

#5 Реклама в постах каждый раз после определенного количества параграфов

Этот пример показывает, как отфильтровать контент и добавить рекламный код после определенного количества параграфов.

# Реклама в постах каждый раз после определенного количества параграфов
add_filter( 'the_content', 'wpse_ad_content' );

function wpse_ad_content( $content ) {

	if( ! is_single() ){
		return $content;
	}

	// Номер абзаца, после которого нужно вставить данные 
	// желательно передать через meta field.
	$paragraphAfter = 5; 
	$return_content = '';
	$ads_block = '<a href="#">ADS</a>';
	$content = explode( "</p>", $content );

	foreach( $content as $i => $value ){

		$return_content .= $value . "</p>";

		if( $i === 0 ){
			$return_content .= $ads_block;
		}

		if( $i === $paragraphAfter ){
			$return_content .= $ads_block;
		}

		if( $i === array_key_last( $content ) ){
			$return_content .= $ads_block;
		}
	}

	return $return_content;
}

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

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

Где вызывается хук

the_content()
the_content
wp_trim_excerpt()
the_content
WP_REST_Revisions_Controller::prepare_item_for_response()
the_content
WP_REST_Posts_Controller::prepare_item_for_response()
the_content
WP_REST_Attachments_Controller::prepare_item_for_response()
the_content
do_trackbacks()
the_content
render_block_core_post_content()
the_content
get_the_content_feed()
the_content
wp-includes/post-template.php 255
$content = apply_filters( 'the_content', $content );
wp-includes/formatting.php 3887
$text = apply_filters( 'the_content', $text );
wp-includes/rest-api/endpoints/class-wp-rest-revisions-controller.php 607
'rendered' => apply_filters( 'the_content', $post->post_content ),
wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php 1857
$data['content']['rendered'] = post_password_required( $post ) ? '' : apply_filters( 'the_content', $post->post_content );
wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php 735
'rendered' => apply_filters( 'the_content', $post->post_content ),
wp-includes/comment.php 2981
$excerpt = apply_filters( 'the_content', $post->post_content, $post->ID );
wp-includes/blocks/post-content.php 55
$content = apply_filters( 'the_content', str_replace( ']]>', ']]&gt;', $content ) );
wp-includes/feed.php 194
$content = apply_filters( 'the_content', get_the_content() );

Где используется хук в WordPress

wp-includes/blocks.php 1095
remove_filter( 'the_content', 'wpautop', $priority );
wp-includes/blocks.php 1115
add_filter( 'the_content', 'wpautop', $current_priority - 1 );
wp-includes/blocks.php 1116
remove_filter( 'the_content', '_restore_wpautop_hook', $current_priority );
wp-includes/blocks.php 1096
add_filter( 'the_content', '_restore_wpautop_hook', $priority + 1 );
wp-includes/class-wp-embed.php 33
add_filter( 'the_content', array( $this, 'run_shortcode' ), 8 );
wp-includes/class-wp-embed.php 41
add_filter( 'the_content', array( $this, 'autoembed' ), 8 );
wp-includes/default-filters.php 189
add_filter( 'the_content', 'prepend_attachment' );
wp-includes/default-filters.php 610
add_filter( 'the_content', 'do_shortcode', 11 ); // AFTER wpautop().
wp-includes/default-filters.php 191
add_filter( 'the_content', 'wp_replace_insecure_home_url' );
wp-includes/default-filters.php 190
add_filter( 'the_content', 'wp_filter_content_tags' );
wp-includes/default-filters.php 185
add_filter( 'the_content', 'wptexturize' );
wp-includes/default-filters.php 188
add_filter( 'the_content', 'shortcode_unautop' );
wp-includes/default-filters.php 187
add_filter( 'the_content', 'wpautop' );
wp-includes/default-filters.php 186
add_filter( 'the_content', 'convert_smilies', 20 );
wp-includes/default-filters.php 184
add_filter( 'the_content', 'do_blocks', 9 );
wp-includes/default-filters.php 154
add_filter( $filter, 'capital_P_dangit', 11 );
wp-includes/template-loader.php 86
remove_filter( 'the_content', 'prepend_attachment' );