The_title — Применяется к заголовку записи, перед тем как вывести заголовок на экран. Используется в функции the_title(). Хук-фильтр WordPress

Опубликовано: 01.09.2018

Применяется к заголовку записи, перед тем как вывести заголовок на экран. Используется в функции the_title() .

В некоторых случаях, например когда используется функция the_title(), заголовок можно удалить, вернув пустое значение в фильтре (NULL, FALSE или '').

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

add_filter( 'the_title', 'filter_function_name_11', 10, 2 ); function filter_function_name_11( $title, $id ) { // Фильтр... return $title; } $title(строка) Заголовок записи. $id(число) ID записи.

Примеры

#1 Добавим слово "Страница" к заголовку постоянных страниц:

Демонстрация работы фильтра:

add_filter( 'the_title', 'add_text_to_page_title' ); function add_text_to_page_title( $title ) { if( is_page() ) $title = 'Страница: '. $title; return $title; }

В результате заголовок всех постоянных страниц будет выглядеть так: Страница: Заголовок страницы.

#2 Удаление заголовков в категории

В этом примере показано, как удалить заголовки у записей, которые находятся в категории "reklama":

function suppress_if_blurb( $title, $id = null ) { if ( in_category('reklama', $id ) ){ return ''; } return $title; } add_filter( 'the_title', 'suppress_if_blurb', 10, 2 );

Дополнительный параметр $id = null, значение по умолчанию для второго параметра, указан потому что, некоторые вызовы функции могут не передавать этот параметр. Эта ошибка появилась в версии 3.1 и была исправлена в версии 3.3. Если нужна обратная совместимость с версиями 3.1-3.3, то нужно указать значение по умолчанию для $id, иначе вы получите PHP предупреждение, что не указан обязательный параметр.

Где используется хук

... * @param WP_Post $post Current post object. */ $private_title_format = apply_filters( 'private_title_format', __( 'Private: %s' ), $post ); $title = sprintf( $private_title_format, $title ); } } /** * Filters the post title. * * @since 0.71 * * @param string $title The post title. * @param int $id The post ID. */ return apply_filters( 'the_title', $title, $id ); } /** * Display the Post Global Unique Identifier (guid). * * The guid will appear to be a link, but should not be used as a link to the * post. The reason you should not use it as a link, is because of moving the * blog across domains. * * URL is escaped to make it XML-safe. * * @since 1.5.0 * * @param int|WP_Post $post Optional. Post ID or post object. Default is global $post. */ ... ... /** * Get original title. * * @since 4.7.0 * * @param object $item Nav menu item. * @return string The original title. */ protected function get_original_title( $item ) { $original_title = ''; if ( 'post_type' === $item->type && ! empty( $item->object_id ) ) { $original_object = get_post( $item->object_id ); if ( $original_object ) { /** This filter is documented in wp-includes/post-template.php */ $original_title = apply_filters( 'the_title', $original_object->post_title, $original_object->ID ); if ( '' === $original_title ) { /* translators: %d: ID of a post */ $original_title = sprintf( __( '#%d (no title)' ), $original_object->ID ); } } } elseif ( 'taxonomy' === $item->type && ! empty( $item->object_id ) ) { $original_term_title = get_term_field( 'name', $item->object_id, $item->object, 'raw' ); if ( ! is_wp_error( $original_term_title ) ) { $original_title = $original_term_title; } } elseif ( 'post_type_archive' === $item->type ) { $original_object = get_post_type_object( $item->object ); if ( $original_object ) { $original_title = $original_object->labels->archives; ... ... return; } if ( empty($post->post_excerpt) ) { /** This filter is documented in wp-includes/post-template.php */ $excerpt = apply_filters( 'the_content', $post->post_content, $post->ID ); } else { /** This filter is documented in wp-includes/post-template.php */ $excerpt = apply_filters( 'the_excerpt', $post->post_excerpt ); } $excerpt = str_replace(']]>', ']]&gt;', $excerpt); $excerpt = wp_html_excerpt($excerpt, 252, '&#8230;'); /** This filter is documented in wp-includes/post-template.php */ $post_title = apply_filters( 'the_title', $post->post_title, $post->ID ); $post_title = strip_tags($post_title); if ( $to_ping ) { foreach ( (array) $to_ping as $tb_ping ) { $tb_ping = trim($tb_ping); if ( !in_array($tb_ping, $pinged) ) { trackback( $tb_ping, $post_title, $excerpt, $post->ID ); $pinged[] = $tb_ping; } else { $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, %s, '')) WHERE ID = %d", $tb_ping, $post->ID ) ); } } } } ... ... * @param WP_Post $item The current menu item. * @param stdClass $args An object of wp_nav_menu() arguments. * @param int $depth Depth of menu item. Used for padding. */ $atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args, $depth ); $attributes = ''; foreach ( $atts as $attr => $value ) { if ( ! empty( $value ) ) { $value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value ); $attributes .= ' ' . $attr . '="' . $value . '"'; } } /** This filter is documented in wp-includes/post-template.php */ $title = apply_filters( 'the_title', $item->title, $item->ID ); /** * Filters a menu item's title. * * @since 4.4.0 * * @param string $title The menu item's title. * @param WP_Post $item The current menu item. * @param stdClass $args An object of wp_nav_menu() arguments. * @param int $depth Depth of menu item. Used for padding. */ $title = apply_filters( 'nav_menu_item_title', $title, $item, $args, $depth ); $item_output = $args->before; $item_output .= '<a'. $attributes .'>'; ... ... $attributes = ''; foreach ( $atts as $attr => $value ) { if ( ! empty( $value ) ) { $value = esc_attr( $value ); $attributes .= ' ' . $attr . '="' . $value . '"'; } } $output .= $indent . sprintf( '<li class="%s"><a%s>%s%s%s</a>', $css_classes, $attributes, $args['link_before'], /** This filter is documented in wp-includes/post-template.php */ apply_filters( 'the_title', $page->post_title, $page->ID ), $args['link_after'] ); if ( ! empty( $args['show_date'] ) ) { if ( 'modified' == $args['show_date'] ) { $time = $page->post_modified; } else { $time = $page->post_date; } $date_format = empty( $args['date_format'] ) ? '' : $args['date_format']; $output .= " " . mysql2date( $date_format, $time ); } } ... ... } elseif ( ( 'postbypost' == $r['type'] ) || ('alpha' == $r['type'] ) ) { $orderby = ( 'alpha' == $r['type'] ) ? 'post_title ASC ' : 'post_date DESC, ID DESC '; $query = "SELECT * FROM $wpdb->posts $join $where ORDER BY $orderby $limit"; $key = md5( $query ); $key = "wp_get_archives:$key:$last_changed"; if ( ! $results = wp_cache_get( $key, 'posts' ) ) { $results = $wpdb->get_results( $query ); wp_cache_set( $key, $results, 'posts' ); } if ( $results ) { foreach ( (array) $results as $result ) { if ( $result->post_date != '0000-00-00 00:00:00' ) { $url = get_permalink( $result ); if ( $result->post_title ) { /** This filter is documented in wp-includes/post-template.php */ $text = strip_tags( apply_filters( 'the_title', $result->post_title, $result->ID ) ); } else { $text = $result->ID; } $output .= get_archives_link( $url, $text, $r['format'], $r['before'], $r['after'] ); } } } } if ( $r['echo'] ) { echo $output; } else { return $output; } } ... ... if ( $object ) { $menu_item->type_label = $object->labels->singular_name; } else { $menu_item->type_label = $menu_item->object; $menu_item->_invalid = true; } if ( 'trash' === get_post_status( $menu_item->object_id ) ) { $menu_item->_invalid = true; } $menu_item->url = get_permalink( $menu_item->object_id ); $original_object = get_post( $menu_item->object_id ); /** This filter is documented in wp-includes/post-template.php */ $original_title = apply_filters( 'the_title', $original_object->post_title, $original_object->ID ); if ( '' === $original_title ) { /* translators: %d: ID of a post */ $original_title = sprintf( __( '#%d (no title)' ), $original_object->ID ); } $menu_item->title = '' == $menu_item->post_title ? $original_title : $menu_item->post_title; } elseif ( 'post_type_archive' == $menu_item->type ) { $object = get_post_type_object( $menu_item->object ); if ( $object ) { $menu_item->title = '' == $menu_item->post_title ? $object->labels->archives : $menu_item->post_title; $post_type_description = $object->description; } else { $menu_item->_invalid = true; ... ... function get_adjacent_post_link( $format, $link, $in_same_term = false, $excluded_terms = '', $previous = true, $taxonomy = 'category' ) { if ( $previous && is_attachment() ) $post = get_post( get_post()->post_parent ); else $post = get_adjacent_post( $in_same_term, $excluded_terms, $previous, $taxonomy ); if ( ! $post ) { $output = ''; } else { $title = $post->post_title; if ( empty( $post->post_title ) ) $title = $previous ? __( 'Previous Post' ) : __( 'Next Post' ); /** This filter is documented in wp-includes/post-template.php */ $title = apply_filters( 'the_title', $title, $post->ID ); $date = mysql2date( get_option( 'date_format' ), $post->post_date ); $rel = $previous ? 'prev' : 'next'; $string = '<a href="' . get_permalink( $post ) . '" rel="'.$rel.'">'; $inlink = str_replace( '%title', $title, $link ); $inlink = str_replace( '%date', $date, $inlink ); $inlink = $string . $inlink . '</a>'; $output = str_replace( '%link', $inlink, $format ); } $adjacent = $previous ? 'previous' : 'next'; /** ... ... _deprecated_function( __FUNCTION__, '2.0.0', 'previous_post_link()' ); if ( empty($in_same_cat) || 'no' == $in_same_cat ) $in_same_cat = false; else $in_same_cat = true; $post = get_previous_post($in_same_cat, $excluded_categories); if ( !$post ) return; $string = '<a href="'.get_permalink($post->ID).'">'.$previous; if ( 'yes' == $title ) $string .= apply_filters('the_title', $post->post_title, $post->ID); $string .= '</a>'; $format = str_replace('%', $string, $format); echo $format; } /** * Prints link to the next post. * * @since 0.71 * @deprecated 2.0.0 Use next_post_link() * @see next_post_link() * * @param string $format * @param string $next * @param string $title ... ... function next_post($format='%', $next='next post: ', $title='yes', $in_same_cat='no', $limitnext=1, $excluded_categories='') { _deprecated_function( __FUNCTION__, '2.0.0', 'next_post_link()' ); if ( empty($in_same_cat) || 'no' == $in_same_cat ) $in_same_cat = false; else $in_same_cat = true; $post = get_next_post($in_same_cat, $excluded_categories); if ( !$post ) return; $string = '<a href="'.get_permalink($post->ID).'">'.$next; if ( 'yes' == $title ) $string .= apply_filters('the_title', $post->post_title, $post->ID); $string .= '</a>'; $format = str_replace('%', $string, $format); echo $format; } /** * Whether user can create a post. * * @since 1.5.0 * @deprecated 2.0.0 Use current_user_can() * @see current_user_can() * * @param int $user_id * @param int $blog_id Not Used * @param int $category_id Not Used ... ... $posts = get_boundary_post($in_same_cat, $excluded_categories, $start); // If there is no post stop. if ( empty($posts) ) return; // Even though we limited get_posts to return only 1 item it still returns an array of objects. $post = $posts[0]; if ( empty($post->post_title) ) $post->post_title = $start ? __('First Post') : __('Last Post'); $date = mysql2date(get_option('date_format'), $post->post_date); $title = str_replace('%title', $post->post_title, $title); $title = str_replace('%date', $date, $title); $title = apply_filters('the_title', $title, $post->ID); $link = $start ? "<link rel='start' title='" : "<link rel='end' title='"; $link .= esc_attr($title); $link .= "' href='" . get_permalink($post) . "' />\n"; $boundary = $start ? 'start' : 'end'; return apply_filters( "{$boundary}_post_rel_link", $link ); } /** * Display relational link for the first post. * * @since 2.8.0 * @deprecated 3.3.0 * ... ... * @return string */ function get_parent_post_rel_link( $title = '%title' ) { _deprecated_function( __FUNCTION__, '3.3.0' ); if ( ! empty( $GLOBALS['post'] ) && ! empty( $GLOBALS['post']->post_parent ) ) $post = get_post($GLOBALS['post']->post_parent); if ( empty($post) ) return; $date = mysql2date(get_option('date_format'), $post->post_date); $title = str_replace('%title', $post->post_title, $title); $title = str_replace('%date', $date, $title); $title = apply_filters('the_title', $title, $post->ID); $link = "<link rel='up' title='"; $link .= esc_attr( $title ); $link .= "' href='" . get_permalink($post) . "' />\n"; return apply_filters( "parent_post_rel_link", $link ); } /** * Display relational link for parent item * * @since 2.8.0 * @deprecated 3.3.0 * * @param string $title Optional. Link title format. Default '%title'. ... ... $indent = ( $depth ) ? str_repeat( "\t", $depth ) : ''; $output .= $indent . '<li>'; $output .= '<label class="menu-item-title">'; $output .= '<input type="checkbox" class="menu-item-checkbox'; if ( ! empty( $item->front_or_home ) ) $output .= ' add-to-top'; $output .= '" name="menu-item[' . $possible_object_id . '][menu-item-object-id]" value="'. esc_attr( $item->object_id ) .'" /> '; if ( ! empty( $item->label ) ) { $title = $item->label; } elseif ( isset( $item->post_type ) ) { /** This filter is documented in wp-includes/post-template.php */ $title = apply_filters( 'the_title', $item->post_title, $item->ID ); if ( ! empty( $item->front_or_home ) && _x( 'Home', 'nav menu home label' ) !== $title ) $title = sprintf( _x( 'Home: %s', 'nav menu front page title' ), $title ); } $output .= isset( $title ) ? esc_html( $title ) : esc_html( $item->title ); $output .= '</label>'; // Menu item hidden fields $output .= '<input type="hidden" class="menu-item-db-id" name="menu-item[' . $possible_object_id . '][menu-item-db-id]" value="' . $possible_db_id . '" />'; $output .= '<input type="hidden" class="menu-item-object" name="menu-item[' . $possible_object_id . '][menu-item-object]" value="'. esc_attr( $item->object ) .'" />'; $output .= '<input type="hidden" class="menu-item-parent-id" name="menu-item[' . $possible_object_id . '][menu-item-parent-id]" value="'. esc_attr( $item->menu_item_parent ) .'" />'; $output .= '<input type="hidden" class="menu-item-type" name="menu-item[' . $possible_object_id . '][menu-item-type]" value="'. esc_attr( $item->type ) .'" />'; $output .= '<input type="hidden" class="menu-item-title" name="menu-item[' . $possible_object_id . '][menu-item-title]" value="'. esc_attr( $item->title ) .'" />'; $output .= '<input type="hidden" class="menu-item-url" name="menu-item[' . $possible_object_id . '][menu-item-url]" value="'. esc_attr( $item->url ) .'" />'; $output .= '<input type="hidden" class="menu-item-target" name="menu-item[' . $possible_object_id . '][menu-item-target]" value="'. esc_attr( $item->target ) .'" />'; ... ... if ( 0 === $this->current_level && (int) $post->post_parent > 0 ) { // Sent level 0 by accident, by default, or because we don't know the actual level. $find_main_page = (int) $post->post_parent; while ( $find_main_page > 0 ) { $parent = get_post( $find_main_page ); if ( is_null( $parent ) ) { break; } $this->current_level++; $find_main_page = (int) $parent->post_parent; if ( ! isset( $parent_name ) ) { /** This filter is documented in wp-includes/post-template.php */ $parent_name = apply_filters( 'the_title', $parent->post_title, $parent->ID ); } } } } $can_edit_post = current_user_can( 'edit_post', $post->ID ); if ( $can_edit_post && $post->post_status != 'trash' ) { $lock_holder = wp_check_post_lock( $post->ID ); if ( $lock_holder ) { $lock_holder = get_userdata( $lock_holder ); $locked_avatar = get_avatar( $lock_holder->ID, 18 ); $locked_text = esc_html( sprintf( __( '%s is currently editing' ), $lock_holder->display_name ) ); } else { ...
rss