Удобный и Быстрый Хостинг для сайтов на WordPress. Пользуюсь сам и вам рекомендую! eurobyte.ru - мощные сервера с Дата-центрами в Нидерландах и Москве. От 159 ₽/мес.

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

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

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

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

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

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

Примеры

2

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

Этот пример можно использовать, для создания постоянной страницы контент которой будет генерироваться в зависимости от чего-либо, допустим переменной $_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'];
}
1

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

Этот пример добавит картинку перед постом (смотрите 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

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

Этот пример показывает, как добавить миниатюру поста перед выводом контента. Миниатюра поста устанавливается при редактировании поста (эта функция должна быть включена, смотрите 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

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

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

# Реклама в постах каждый раз после определенного количества параграфов
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;
}
-1

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

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

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

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

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

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

the_content()
the_content
insert_hooked_blocks_into_rest_response()
the_content
render_block_core_post_content()
the_content
get_the_content_feed()
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
wp_trim_excerpt()
the_content
do_trackbacks()
the_content
wp-includes/post-template.php 256
$content = apply_filters( 'the_content', $content );
wp-includes/blocks.php 1506-1509
$response->data['content']['rendered'] = apply_filters(
	'the_content',
	$response->data['content']['raw']
);
wp-includes/blocks/post-content.php 50
$content = apply_filters( 'the_content', str_replace( ']]>', ']]&gt;', $content ) );
wp-includes/feed.php 196
$content = apply_filters( 'the_content', get_the_content() );
wp-includes/rest-api/endpoints/class-wp-rest-revisions-controller.php 683
$data['content']['rendered'] = apply_filters( 'the_content', $post->post_content );
wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php 2007
$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 920
'rendered' => apply_filters( 'the_content', $post->post_content ),
wp-includes/formatting.php 3983
$text = apply_filters( 'the_content', $text );
wp-includes/comment.php 3113
$excerpt = apply_filters( 'the_content', $post->post_content, $post->ID );

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

wp-includes/blocks.php 1502
remove_filter( 'the_content', 'apply_block_hooks_to_content_from_post_object', $priority );
wp-includes/blocks.php 1513
add_filter( 'the_content', 'apply_block_hooks_to_content_from_post_object', $priority );
wp-includes/blocks.php 2528
remove_filter( 'the_content', 'wpautop', $priority );
wp-includes/blocks.php 2529
add_filter( 'the_content', '_restore_wpautop_hook', $priority + 1 );
wp-includes/blocks.php 2548
add_filter( 'the_content', 'wpautop', $current_priority - 1 );
wp-includes/blocks.php 2549
remove_filter( 'the_content', '_restore_wpautop_hook', $current_priority );
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 171
add_filter( $filter, 'capital_P_dangit', 11 );
wp-includes/default-filters.php 201
add_filter( 'the_content', 'apply_block_hooks_to_content_from_post_object', 8 ); // BEFORE do_blocks().
wp-includes/default-filters.php 202
add_filter( 'the_content', 'do_blocks', 9 );
wp-includes/default-filters.php 203
add_filter( 'the_content', 'wptexturize' );
wp-includes/default-filters.php 204
add_filter( 'the_content', 'convert_smilies', 20 );
wp-includes/default-filters.php 205
add_filter( 'the_content', 'wpautop' );
wp-includes/default-filters.php 206
add_filter( 'the_content', 'shortcode_unautop' );
wp-includes/default-filters.php 207
add_filter( 'the_content', 'prepend_attachment' );
wp-includes/default-filters.php 208
add_filter( 'the_content', 'wp_replace_insecure_home_url' );
wp-includes/default-filters.php 209
add_filter( 'the_content', 'do_shortcode', 11 ); // AFTER wpautop().
wp-includes/default-filters.php 210
add_filter( 'the_content', 'wp_filter_content_tags', 12 ); // Runs after do_shortcode().
wp-includes/formatting.php 3974
$filter_image_removed = remove_filter( 'the_content', 'wp_filter_content_tags', 12 );
wp-includes/formatting.php 3980
$filter_block_removed = remove_filter( 'the_content', 'do_blocks', 9 );
wp-includes/formatting.php 3988
add_filter( 'the_content', 'do_blocks', 9 );
wp-includes/formatting.php 3997
add_filter( 'the_content', 'wp_filter_content_tags', 12 );
wp-includes/template-loader.php 96
remove_filter( 'the_content', 'prepend_attachment' );
8 комментариев