get_post_class() WP 2.7.0

Отримує css класи у вигляді масиву, які потрібно використовувати в записі для виведення в html тезі.

Підсумковий масив класів пропускається через фільтр post_class, використовуйте його, коли потрібно змінити класи, що виводяться в залежності від різних умов.

Щоб одразу вивести класи на екран у вигляді рядка, використовуйте post_class()

Де та які класи додаються
  • hentry, post-{$post_id}, type-{$post_type}, status-{$post_status}, {$post_type}— виводяться всім записів. Частини у дужках замінюються на відповідну змінну поточного запису;
    {$post_type} НЕ виводиться в адмінці…

  • sticky– якщо це приліплений піст, виводиться лише на сторінці is_home() . В адмінці виводиться status-sticky;

  • has-post-thumbnail— якщо запис має мініатюру;

  • format-{формат записи}— якщо активовано підтримку форматів. Якщо формат не вказано, то виведе format-standart.

  • post-password-required– Для записів захищених паролем.

  • {$taxonomy}-{$slug}– Якщо запис належить таксономії. $taxonomy заміниться назвою такси, а $slug назвою терміна (елемента таксономії). Наприклад: category-blog;
    Винятком тут є таксономія post_tagдля неї префікс буде tag-, а не post_tag-. Наприклад: tag-novosti.
Основа для:
post_class()
1 раз – 0.00616 сек
(дуже повільно) | 50000 разів – 10.72 сек
(повільно) |
PHP 7.0.2, WP 4.4.1

Хуки з функції
get_post_class($class, $post_id);
$class
(рядок/масив)
Класи, які потрібно додати до списку.


За замовчуванням: ”
$post_id
(число/WP_Post)
ID або об’єкт запису, класи якого потрібно отримати.


Типово: null

Приклади

0

#1 Демонстрація висновку

$classes = get_post_class(); print_r($classes); /* Array ( [0] => post-219 [1] => post [2] => type-post [3] => status-publish [4] => format-standard [5] => has-post-thumbnail [6] => hentry [7] => category-blog [8] => tag-novosti ) */
0

#2 Виведемо всі класи у вигляді рядка

Цей код можна використовувати як заміну для post_class() :

echo '<div class="' . join(' ', get_post_class() ) . '">';
0

#3 Додамо свій клас

$classes = get_post_class('foo bar'); // або можна масивом $classes = get_post_class( array('foo', 'bar') ); /* Обидва приклади додадуть до загального масиву Array ( [0] => foo [1] => bar [2] => post-19 ) */
0

#4 Видалимо непотрібний клас

Допустимо нам потрібно позбутися класу hentry, тоді перед викликом get_post_class() або post_class() використовуйте такий фільтр:

add_filter( 'post_class', 'remove_hentry'); function remove_hentry( $classes ) { $unset = array('hentry'); // можна додати ще return array_diff($classes, $unset); }

нотатки

  • З версії 3.1 введено підтримку форматів постів.
  • З версії 4.2 введено підтримку таксономій.

список змін

З версії 2.7.0Введено.
З версії 4.2.0Custom taxonomy class names були added.

Код get_post_class() WP 6.0.2

function get_post_class( $class = '', $post_id = null ) { $post = get_post($post_id); $classes = array(); if ($class) { if ( ! is_array( $class ) ) { $class = preg_split( '#s+#', $class ); } $classes = array_map( 'esc_attr', $class ); } else { // Ensure that we always coerce class to being an array. $class = array(); } if (! $post) { return $classes; } $classes[] = 'post-'. $post->ID; if ( ! is_admin() ) { $classes[] = $post->post_type; } $classes[] = 'type-'. $post->post_type; $classes[] = 'status-'. $post->post_status; // Post Format. if ( post_type_supports( $post->post_type, 'post-formats' ) ) { $post_format = get_post_format($post->ID); if ( $post_format && ! is_wp_error( $post_format ) ) { $classes[] = 'format-'. sanitize_html_class($post_format); } else { $classes[] = 'format-standard'; } } $post_password_required = post_password_required( $post->ID ); // Post requires password. if ( $post_password_required ) { $classes[] = 'post-password-required'; } elseif ( ! empty( $post->post_password ) ) { $classes[] = 'post-password-protected'; } // Post thumbnails. if ( current_theme_supports( 'post-thumbnails' ) && has_post_thumbnail( $post->ID ) && ! is_attachment( $post ) && ! $post_password_required ) { $classes[] = 'has-post-thumbnail'; } // Sticky for Sticky Posts. if ( is_sticky( $post->ID ) ) { if ( is_home() && ! is_paged() ) { $classes[] = 'sticky'; } elseif ( is_admin() ) { $classes[] = 'status-sticky'; } } // Hentry for hAtom compliance. $classes[] = 'hentry'; // Всі громадські taxonomies. $taxonomies = get_taxonomies( array( 'public' => true ) ); foreach ((array) $taxonomies as $taxonomy) { if ( is_object_in_taxonomy( $post->post_type, $taxonomy ) ) { foreach ((array) get_the_terms( $post->ID, $taxonomy ) as $term ) { if (empty($term->slug)) { continue; } $term_class = sanitize_html_class( $term->slug, $term->term_id ); if ( is_numeric( $term_class ) || ! trim( $term_class, '-' ) ) { $term_class = $term->term_id; } // 'post_tag' використовує 'tag' prefix for backward compatibility. if ( 'post_tag' === $taxonomy ) { $classes[] = 'tag-'. $term_class; } else { $classes[] = sanitize_html_class( $taxonomy . '-' . $term_class, $taxonomy . '-' . $term->term_id ); } } } } $classes = array_map( 'esc_attr', $classes ); /** * Filters the list of CSS class names for current post. * * @ Since 2.7.0 * * @param string[] $classes На array of post class names. * @param string[] $class An array of additional class names added to the post. * @param int $post_id The post ID. */ $classes = apply_filters( 'post_class', $classes, $class, $post->ID ); return array_unique($classes); }

Залишити відповідь

Ваша e-mail адреса не оприлюднюватиметься. Обов’язкові поля позначені *