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

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

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

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

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

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

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

Примеры

1

#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'];
}
0

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

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

add_filter('the_content', 'the_end');
function the_end( $text ){
	return $text . ' Конец!';
}
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 256
$content = apply_filters( 'the_content', $content );
wp-includes/formatting.php 3992
$text = apply_filters( 'the_content', $text );
wp-includes/rest-api/endpoints/class-wp-rest-revisions-controller.php 620
'rendered' => apply_filters( 'the_content', $post->post_content ),
wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php 1863
$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 744
'rendered' => apply_filters( 'the_content', $post->post_content ),
wp-includes/comment.php 2983
$excerpt = apply_filters( 'the_content', $post->post_content, $post->ID );
wp-includes/blocks/post-content.php 48
$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 1528
remove_filter( 'the_content', 'wpautop', $priority );
wp-includes/blocks.php 1529
add_filter( 'the_content', '_restore_wpautop_hook', $priority + 1 );
wp-includes/blocks.php 1548
add_filter( 'the_content', 'wpautop', $current_priority - 1 );
wp-includes/blocks.php 1549
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 162
add_filter( $filter, 'capital_P_dangit', 11 );
wp-includes/default-filters.php 192
add_filter( 'the_content', 'do_blocks', 9 );
wp-includes/default-filters.php 193
add_filter( 'the_content', 'wptexturize' );
wp-includes/default-filters.php 194
add_filter( 'the_content', 'convert_smilies', 20 );
wp-includes/default-filters.php 195
add_filter( 'the_content', 'wpautop' );
wp-includes/default-filters.php 196
add_filter( 'the_content', 'shortcode_unautop' );
wp-includes/default-filters.php 197
add_filter( 'the_content', 'prepend_attachment' );
wp-includes/default-filters.php 198
add_filter( 'the_content', 'wp_replace_insecure_home_url' );
wp-includes/default-filters.php 199
add_filter( 'the_content', 'do_shortcode', 11 ); // AFTER wpautop().
wp-includes/default-filters.php 200
add_filter( 'the_content', 'wp_filter_content_tags', 12 ); // Runs after do_shortcode().
wp-includes/formatting.php 3983
$filter_image_removed = remove_filter( 'the_content', 'wp_filter_content_tags', 12 );
wp-includes/formatting.php 3989
$filter_block_removed = remove_filter( 'the_content', 'do_blocks', 9 );
wp-includes/formatting.php 3997
add_filter( 'the_content', 'do_blocks', 9 );
wp-includes/formatting.php 4006
add_filter( 'the_content', 'wp_filter_content_tags', 12 );
wp-includes/template-loader.php 86
remove_filter( 'the_content', 'prepend_attachment' );
8 комментариев
    Войти