the_content хук-фильтр . WP 1.2.1
Используется для фильтрации контента записи, после того как контент получен из базы данных, но до того как он будет выведет на экран.
Всегда обращайте внимание на то, чтобы передаваемая переменная $content была возвращена обратно после обработки, иначе пользователи увидят пустую страницу.
Использование
add_filter( 'the_content', 'filter_function_name_11' ); function filter_function_name_11( $content ) { // Фильтр... return $content; }
- $content(строка)
- Строка, которую нужно отфильтровать и вернуть обратно.
Примеры
#1 Демонстрация работы
Для демонстрации работы фильтра, добавим в конец каждого текста поста надпись " Конец!":
add_filter('the_content', 'the_end'); function the_end( $text ){ return $text . ' Конец!'; }
#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']; }
#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; }
#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; }
Где вызывается хук
$excerpt = apply_filters( 'the_content', $post->post_content, $post->ID );
$content = apply_filters( 'the_content', get_the_content() );
'rendered' => apply_filters( 'the_content', $post->post_content ),
'rendered' => apply_filters( 'the_content', $post->post_content ),
$data['content']['rendered'] = post_password_required( $post ) ? '' : apply_filters( 'the_content', $post->post_content );
$content = apply_filters( 'the_content', $content );
$text = apply_filters( 'the_content', $text );
Где используется хук в ядре WordPress
remove_filter( 'the_content', 'wpautop', $priority );
add_filter( 'the_content', 'wpautop', $current_priority - 1 );
remove_filter( 'the_content', '_restore_wpautop_hook', $current_priority );
add_filter( 'the_content', '_restore_wpautop_hook', $priority + 1 );
add_filter( 'the_content', array( $this, 'run_shortcode' ), 8 );
add_filter( 'the_content', array( $this, 'autoembed' ), 8 );
add_filter( 'the_content', 'prepend_attachment' );
add_filter( 'the_content', 'do_shortcode', 11 ); // AFTER wpautop().
add_filter( 'the_content', 'wp_replace_insecure_home_url' );
add_filter( 'the_content', 'wp_filter_content_tags' );
add_filter( 'the_content', 'wptexturize' );
add_filter( 'the_content', 'shortcode_unautop' );
add_filter( 'the_content', 'wpautop' );
add_filter( 'the_content', 'convert_smilies', 20 );
add_filter( 'the_content', 'do_blocks', 9 );
add_filter( $filter, 'capital_P_dangit', 11 );
remove_filter( 'the_content', 'prepend_attachment' );