Php get wordpress content

Get WordPress post content by post id

@Bainternet I’m just curious here. what is the part $content = str_replace(‘]]>’, ‘]]>’, $content); do? what’s the purpose of it there?

@AverageJoe its basic search and replace. When using the_content() the content is filtered. Since in the above example the content was directly retrieved, the author has used the search and replace to make it safe.

maybe you also need do_shortcode() like $content = do_shortcode(get_post_field(‘post_content’, $my_postid));

echo get_post_field('post_content', $post_id); 

better to do it like echo apply_filters(‘the_content’, get_post_field(‘post_content’, $post_id)); . For example when using qTranslate, your solution would not be enough.

Without the code from @KarelAttl line breaks where missing. With the apply_filters code it worked perfectly.

apply_filters is a good option, but wasn’t right for my current purpose. It’s good to have both options.

Another way to get a WordPress post content by post id is:

$content = apply_filters('the_content', get_post_field('post_content', $my_postid)); 

To complete this answer I have also added method 01 and method 02 to this answer.

$content_post = get_post($my_postid); $content = $content_post->post_content; $content = apply_filters('the_content', $content); $content = str_replace(']]>', ']]>', $content); 
$content = get_post_field('post_content', $my_postid); 
$content = apply_filters('the_content', get_post_field('post_content', $my_postid)); 

Read the What is the best / efficient way to get WordPress content by post id and why? question to get an idea about which one you should use from the above three.

Источник

get_the_content() │ WP 0.71

Получает контент текущей записи (поста). Используется внутри Цикла WordPress. Когда функция используется на страницах архивов (не отдельная страница записи) и если в контенте используется тег-разделитель , то эта функция выведет не весь контент, а только текст до тега с последующей ссылкой «читать дальше» (текст ссылки можно изменить через параметр $more_link_text ). Не фильтрует контент, как это делает the_content(). Поэтому, если нужно получить результат с применением к контенту всех хуков the_content , используйте конструкцию:

$content = apply_filters( 'the_content', get_the_content() );
Хуки из функции

Возвращает

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

get_the_content( $more_link_text, $strip_teaser, $post );

$more_link_text(строка) Текст ссылки для места обрыва статьи (читать далее).
По умолчанию: null $strip_teaser(логический) Под словом teaser понимается привлекающий текст до тега more. strip_teaser — значит удалить этот текст. Т.е., если установить параметр в true, то контент до тега на is_single() странице будет удален. По умолчанию параметр отключен. Его также можно включить, указав в любом месте текста записи (принято указывать сразу после тега ).
По умолчанию: null $post(WP_Post/Объект/число) (с версии 5.2) Запись (пост), контент которой нужно получить.
По умолчанию: null

Примеры

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

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

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

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

$the_content = apply_filters( ‘the_content’, get_the_content() ); if ( ! empty( $the_content ) )
$post = get_post( 12 ); // specific post $the_content = apply_filters( ‘the_content’, $post->post_content ); if ( ! empty( $the_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 tag.
  • Global. int. $multipage Boolean indicator for whether multiple pages are in play.

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

Код get_the_content() get the content WP 6.2.2

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( '%2$s', sprintf( /* translators: %s: Post title. */ __( 'Continue reading %s' ), the_title_attribute( array( 'echo' => false, 'post' => $_post, ) ) ), __( '(more…)' ) ); > $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( '//', $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( '//', '', $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 ( false !== strpos( $_post->post_content, '' ) && ( ! $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 .= 'ID . '">' . $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', ' ID>\" $more_link_text ); > $output = force_balance_tags( $output ); > > return $output; >

Cвязанные функции

loop (Цикл WP)

  • get_the_author()
  • get_the_author_link()
  • get_the_excerpt()
  • get_the_ID()
  • get_the_tag_list()
  • get_the_tags()
  • setup_postdata()
  • the_author()
  • the_content()
  • the_date()
  • the_excerpt()
  • the_ID()
  • the_permalink()
  • the_post()
  • the_tags()
  • the_time()

Записи: посты, страницы, .

  • edit_post_link()
  • get_delete_post_link()
  • get_edit_post_link()
  • get_permalink()
  • get_post_field()
  • get_post_status()
  • get_post_time()
  • get_sample_permalink()
  • get_the_date()
  • get_the_modified_date()
  • get_the_modified_time()
  • get_the_permalink()
  • get_the_time()
  • get_the_title()
  • get_the_title_rss()
  • has_excerpt()
  • post_password_required()
  • register_post_status()
  • single_post_title()
  • the_excerpt_rss()
  • the_modified_date()
  • the_title()
  • the_title_attribute()

Источник

get_the_content() — возвращает контент поста

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

Используйте внутри цикла WordPress для получения содержимого текущей записи, либо передайте ID определённого поста в качестве параметра.

get_the_content( $more_link_text = null, $strip_teaser = false, $post = null )

Параметры

$more_link_text (строка) Позволяет установить собственный текст ссылки перехода к полной версии поста. По умолчанию анкор ссылки в русской версии WordPress — (далее. ) . $strip_teaser (логическое) Влияет на то, как отображается полная версия контента (то есть то, что обычно находится в single.php ):

  • false — по умолчанию полная версия содержимого поста выводится как обычно.
  • true — в этом случае в полной версии поста будет отсутствовать часть контента, которая находится до тега .

Пример 1. Выводим контент страницы без фильтров

$content_no_filter = get_the_content( 'Перейти к посту. ' ); echo $content_no_filter;

Главное отличие функции get_the_content() от the_content() не в том, что первая функция возвращает результат, а вторая выводит, а в том, что the_content() применяет огромное количество действий на фильтр the_content – там и интерпретация шорткодов, и замена кавычек и многое другое.

Пример 2. Как записать в переменную отфильтрованый контент

Для того, чтобы получить контент записи или страницы с применением всех фильтров, то вы можете использовать следующий код:

$content_no_filter = get_the_content(); // содержимое поста (текущего в цикле) из базы $content = apply_filters( 'the_content', $content_no_filter ); // применяем фильтр the_content

Либо буферизацию на функцию the_content():

ob_start(); the_content(); $content = ob_get_contents(); // переменная $content теперь содержит контент записи ob_end_clean();

Пример 3. Вывод содержимого записи/страницы с определённым ID

До версии WordPress 5.2 нам нужно было придумывать что-то в этом роде:

$post_id = 5; // пост с определённым ID $post = get_post( $post_id ); $content = apply_filters('the_content', $post->post_content);

Теперь же всё изменилось с приходом третьего параметра в функцию:

$post_id = 5; $content = get_the_content( null, false, $post_id );

Глобальные переменные

Функция кстати работает со следующими глобальными переменными:

$page (целое) Номер подстраницы при разделении поста по подстраницам тегом $more (логическое) Нужно ли отображать целиком пост или только отрывок до тега . Подробное описание этой глобальной переменной в примере. $pages (массив) Массив контента каждой из подстраниц контента поста, разделённых тегом . $multipage (логическое) Существует ли разделение контента на подстраницы.

Как же так, ведь текст кнопки «Далее» можно указать в первом параметре функции the_content() ? Дело в том, что там вы можете указать только текст ссылки, а фильтр the_content_more_link позволяет полностью изменить её HTML код.

В качестве примера добавим к ссылке «Далее» HTML-атрибут target=»_blank» .

Миша

Впервые познакомился с WordPress в 2009 году. Организатор и спикер на конференциях WordCamp. Преподаватель в школе Нетология.

Пишите, если нужна помощь с сайтом или разработка с нуля.

Источник

Читайте также:  Php variable variables this
Оцените статью