WordPress php display content

Содержание
  1. Php display content in post field wordpress
  2. WordPress hook to pre-populate the content field on post-new.php?
  3. How can I display the Most Viewed posts in WordPress?
  4. The correct way to display Pods 2.0 items using PHP code in a Pods template
  5. Display custom field in product (wordpress)
  6. the_content() │ WP 0.71
  7. Возвращает
  8. Использование
  9. Примеры
  10. #2 Изменение текста ссылки «читать дальше. «
  11. #3 Вставка заголовка статьи в текст ссылки «читать дальше. «
  12. #4 Игнорируем тег «more» для прилепленных записей (sticky)
  13. #5 Альтернативное использование
  14. Список изменений
  15. Код the_content() the content WP 6.2.2
  16. Cвязанные функции
  17. loop (Цикл WP)
  18. Записи: посты, страницы, .
  19. Записи: посты, страницы, .
  20. WordPress: вывод в шаблон записи
  21. ID записи
  22. URL текущий страницы
  23. Название / H1
  24. Текст
  25. Изображение
  26. Тег .
  27. URL изображения.
  28. ID и данные о картинке.
  29. Результат
  30. Произвольные поля
  31. Текстовые и численные поля.
  32. Изображения.
  33. Файлы.
  34. Повторитель полей.
  35. Для текстовых значений
  36. Для изображений и файлов
  37. Рубрики / категории
  38. Список ссылок.
  39. Результат
  40. Результат
  41. Метки / теги
  42. Вывод записей из той же категории
  43. How to Display All Your WordPress Posts on One Page

Php display content in post field wordpress

setPostViews() function add or update the post meta with post_views_count meta key. single.php File Open the single.php file from activated theme directory and place the setPostViews() function inside the loop. Solution 1: Not exactly sure I have grasped your point, but if the difference between an Q and A entry and a KB entry is more than just a flag in the table, eg it is a largely a copy operation from one table to another: Couldnt you simply use Mysqls INSERT INTO ability?

WordPress hook to pre-populate the content field on post-new.php?

Not exactly sure I have grasped your point, but if the difference between an Q and A entry and a KB entry is more than just a flag in the table, eg it is a largely a copy operation from one table to another: Couldnt you simply use Mysqls INSERT INTO ability? http://dev.mysql.com/doc/refman/5.5/en/insert-select.html which is triggered by the user posting back just the id of the Q and A article?

Читайте также:  Earthquake Markers

It turns out the filter hook I was looking for is the_editor_content , which will (as its name suggests) let me manipulate the content that gets placed in the editor.

I think you need to hook into default_content like this

add_filter( 'default_content', 'my_editor_content' ); function my_editor_content( $content )

Php — WordPress Advanced Custom Fields, You want to make a call to the wp query and find the current post ID, and then use a variable to find the field for that post ID (current page — or a specified ID if …

How can I display the Most Viewed posts in WordPress?

Open the functions.php file of the activated theme and add the following code.

setPostViews() function add or update the post meta with post_views_count meta key.

/* * Set post views count using post meta */ function setPostViews($postID) < $countKey = 'post_views_count'; $count = get_post_meta($postID, $countKey, true); if($count=='')< $count = 0; delete_post_meta($postID, $countKey); add_post_meta($postID, $countKey, '0'); >else < $count++; update_post_meta($postID, $countKey, $count); >> 

Open the single.php file from activated theme directory and place the setPostViews() function inside the loop.

Display the Most Viewed Posts

The following query will fetch the posts based on the post_views_count meta key value. Place the following code in the sidebar or where you want to display the most popular posts list.

WordPress — The correct way to display Pods 2.0 items, We deprecated PHP in templates, we’re moving towards Twig templating which will allow much more versatile templating processes. As far as …

The correct way to display Pods 2.0 items using PHP code in a Pods template

You aren’t giving pods() the ID of the post you want to use. But your main issue is that you don’t need to setup a new pods() object at all, you just need to use this:

$obj references the current Pods object used, when in a template.

Also, I’m using display here, because it will then run any filters that the_title() would normally run, when in Pods.

Php — Display related post content and custom field, I’m having trouble trying to display related post content and custom field content from one custom post type to another. The Custom Post Types and …

Display custom field in product (wordpress)

Since query_posts() is used, you have to put wp_reset_query(); after the endwhile() . Otherwise use WP_Query .

have_posts()) : $query->the_post(); ?>

Php — Display WordPress Custom post by Meta Data, app-key | 122334455669. 02.user-key | xjsk284k38dj. etc. They have 00, 01, 02, etc so they appear in alphanumeric order as there are a number … Code sample’showposts’ => 5,’post_type’ => ‘foodswaps’,’meta_key’ => ’00.event-date’,’orderby’ => ‘meta_value’,’meta_query’ => array(Feedback

Источник

the_content() │ WP 0.71

Выводит контент текущего поста (записи). Тег шаблона, должен использоваться внутри Цикла WordPress или на странице записи (page.php, single.php), в начале которой вызвана функция the_post(). Когда функция используется на страницах архивов (не отдельная страница записи) и если в контенте используется тег-разделитель , то эта функция выведет не весь контент, а только текст до тега с последующей ссылкой «читать дальше» (текст ссылки можно изменить через параметр $more_link_text ).

Хуки из функции

Возвращает

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

$more_link_text(строка) Текст, который будет показан как текст ссылки, вместо ‘(читать дальше. )’.
По умолчанию: ‘(читать дальше. )’ $strip_teaser(логический) Под словом «teaser» понимается привлекающий текст до тега . strip_teaser — значит удалить этот текст. Если установить параметр в true, то контент до тега на странице is_single() будет удален. Аналогично можно удалить контент до тега more, указав в любом месте кода статьи тег . Обычно его принято указывать сразу после тега . По умолчанию: false

Примеры

#1 Изменение поведения функции, относительно обрезки текста по тегу

Если функция не режет текст по тегу или наоборот, режет, где нам это не нужно, то можно изменить переменную $more, тем самым указав функции резать (0) или не резать (1) текст.

#2 Изменение текста ссылки «читать дальше. «

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

#3 Вставка заголовка статьи в текст ссылки «читать дальше. «

Можно использовать Тег шаблона the_title() , чтобы вставить в текст ссылки «читать дальше. » заголовок записи:

#4 Игнорируем тег «more» для прилепленных записей (sticky)

Этот пример будет выводить весь контент для прилепленных записей (даже если в них есть тег «more»), но остальных записей текст будет обрезаться:

#5 Альтернативное использование

Если нужно получить контент записи для обработки, а не выводить его на экран, то можно использовать функцию get_the_content() :

Однако надо иметь ввиду, что полученный контент (который сейчас в переменной $content) не будет отфильтрован. Чтобы его отфильтровать его нужно «прогнать» через фильтр ‘the_content’:

$content = apply_filters( 'the_content', $content ); $content = str_replace( ']]>', ']]>', $content );

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

Код the_content() the content WP 6.2.2

function the_content( $more_link_text = null, $strip_teaser = false ) < $content = get_the_content( $more_link_text, $strip_teaser ); /** * Filters the post content. * * @since 0.71 * * @param string $content Content of the current post. */ $content = apply_filters( 'the_content', $content ); $content = str_replace( ']]>', ']]>', $content ); echo $content; >

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

loop (Цикл WP)

  • get_the_author()
  • get_the_author_link()
  • get_the_content()
  • get_the_excerpt()
  • get_the_ID()
  • get_the_tag_list()
  • get_the_tags()
  • setup_postdata()
  • the_author()
  • 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()

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

  • body_class()
  • get_post_format()
  • has_post_parent()
  • have_posts()
  • in_the_loop()
  • next_image_link()
  • next_post_link()
  • next_posts_link()
  • post_class()
  • posts_nav_link()
  • previous_image_link()
  • previous_post_link()
  • previous_posts_link()
  • single_month_title()
  • the_category()
  • the_modified_author()
  • the_post_navigation()
  • the_search_query()
  • the_shortlink()
  • wp_get_shortlink()
  • wp_link_pages()

Можно ли какую-то более быструю альтернативу the_content найти? get_the_content тоже медленная, к сожалению.

Смотря что нужно. Как вариант поотключать ненужные хуки, или наоборот (чтобы плагины не втыкались) сделать свою функцию, которая будет применять только нужные хуки. Еще вариант — кэшировать все это дело.

Источник

WordPress: вывод в шаблон записи

В данной статье представлены примеры вывода информации на странице записи WordPress.

В качестве шаблона для вывода записи используется файл:
/wp-content/themes/название_темы/single.php , если его нет то index.php

Далее представлен базовый шаблон. Данные поста выводятся в цикле have_posts() , поэтому не нужно указывать $id в функциях вывода контента.

ID записи

URL текущий страницы

$url = get_the_permalink(); echo $url;

Название / H1

$h1 = get_the_title(); echo $h1;

Текст

$content = get_the_content(); echo $content;

Изображение

Тег .

$img = get_the_post_thumbnail(null, 'full'); echo $img;

Размер изображения можно задать следующие:

thumbnail маленькая
medium средняя
large большая
full оригинал
array(100, 100) произвольный размер

URL изображения.

$src = get_the_post_thumbnail_url(null, 'full'); echo $src;

Вывод превьюшки с ссылкой на оригинал.

ID и данные о картинке.

Функция wp_get_attachment_image_src($id, $size) возвращает массив данных картинки по ID.

$thumb_id = get_post_thumbnail_id(); $src = wp_get_attachment_image_src($thumb_id, 'full'); print_r($src);

Результат

Array ( [0] => http://example.com/wp-content/uploads/image.png [1] => 150 [2] => 111 [3] => 1 )

Произвольные поля

Текстовые и численные поля.

Изображения.

Файлы.

Повторитель полей.

Для текстовых значений

Для изображений и файлов

Рубрики / категории

Список ссылок.

the_category($id) и get_the_category_list($id) – выведут список ссылок рубрик.

$category = get_the_category_list(); echo $category;

Результат

get_the_category($id) – вернет массив категорий.

$category = get_the_category(); print_r($category);

Результат

Array ( [0] => WP_Term Object ( [term_id] => 4 [name] => Раздел 1 [slug] => razdel-1 [term_group] => 0 [term_taxonomy_id] => 4 [taxonomy] => category [description] => [parent] => 0 [count] => 1 [filter] => raw [cat_ID] => 4 [category_count] => 1 [category_description] => [cat_name] => Раздел 1 [category_nicename] => razdel-1 [category_parent] => 0 ) . )

На основе этой функции можно вывести список категорий с изображениями и текстом. Картинки к рубрикам добавляются с помощью плагина произвольных полей.

 
Ссылка и название: cat_ID); ?>"> name; ?> Текст: category_description; ?>
?>

Метки / теги

Функции the_tags() и get_the_tag_list() выведут ссылки с тегами к которым привязана запись.

echo get_the_tag_list('

Метки: ',', ','

');

get_the_tags($id) – возвращает массив тегов.

$tags = get_the_tags(); print_r($tags);
Array ( [0] => WP_Term Object ( [term_id] => 24 [name] => Тег 1 [slug] => teg-1 [term_group] => 0 [term_taxonomy_id] => 24 [taxonomy] => post_tag [description] => [parent] => 0 [count] => 1 [filter] => raw ) )

Вывод записей из той же категории

Следующий пример с помощью функции WP_Query() выведет 6 последних записей из категории текущей записи с картинками.

 'post', 'post_status' => 'publish', 'posts_per_page' => 6, 'cat' => $category[0]->cat_ID, 'post__not_in' => array(get_the_ID()), 'orderby' => 'date', 'order' => 'DESC' ) ); if ($query->have_posts()) < while ($query->have_posts()) < $query->the_post(); ?> "> Картинка Превью wp_reset_postdata(); > ?>

Источник

How to Display All Your WordPress Posts on One Page

How to Show All Your WordPress Posts on One Page

Apart from producing engaging and insightful content, WordPress bloggers have to constantly work on retaining their readers. One way to do it is by making pages that contain all your posts, with the latest ones on top or with your posts arranged in a specific order. By doing so you are ensuring that your readers, after finishing an article they enjoyed, can find additional relevant content. The benefits are quite clear – your posts will have more views, giving you greater reach and the possibility to achieve a bigger revenue from ads and affiliate links.

Displaying your posts in a grid layout can be a good call from the UX standpoint, as grid layouts make your pages appear tidy, neat and organized. Another thing you can consider for your post pages is the “Load more posts” button, which is ideal for blogs with a lot of content. Displaying them all on one page would be a mess, so the button visitors can click to see another batch of posts is a great UX fix.

That being said, it’s important to understand that not all websites and not all blogs can benefit from having all the posts displayed on a single page. For big blogs with a long track record and hundreds or even thousands of posts, this can’t possibly be a good idea. In such situations, it’s much better to provide access to the blog archive via a sidebar shortcode, for instance.

In any case, we’re here today to show you how to display all your WordPress posts on one page, so let’s get down to it.

Источник

Оцените статью