and

Get the Post/Page Title in WordPress using PHP

If you are developing custom WordPress functionality one important element is a post or page’s title. Luckily WordPress has a built in function to retrieve the title of the current post using PHP. This is useful for displaying a post title in a custom loop or in other areas of your WordPress site’s theme.

In this article I’ll be going over how to use the get_the_title() function in WordPress.

How to Display the Page/Post Title in PHP

Now let’s dive in and use get_the_title() to display our page/post’s title in WordPress using PHP. This is useful if you’re creating a custom theme or custom code snippet. Best of all the function will output the title of any post type including pages and posts. If you add custom post types to your site it’ll also work for retrieving their title as well.

You can easily echo the get_the_title function and it’ll output the current global $post object’s title. This will work in most use cases and likely what you need.

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

// Display post title
echo get_the_title();

Alternatively you can set the post ID in the get_the_title function to get a specific post’s title. You can see in the examples below how I am getting a post/page’s title by ID. This works great too if you have a custom loop you’ve created and want to grab the title that way.

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

// Display post title using post ID
echo get_the_title( 5 );
// Display post title and safely escape value
echo esc_html( get_the_title() );
// Using the_title function to automatically echo the title, while you can append or prepend the title using the function as displayed below
the_title( ‘Before:’ , ‘ — After’ )

I’ve also included an example of the_title() function which outputs the title without using echo. the_title() function also allows you to include content before and after the title as seen in the example above. Typically I recommend using get_the_title() so you can modify the title string if needed.

If you use get_the_title() function on a password protected or private post the words “Protected” and “Private” will be inserted before the post title.

If you’re using the title as a title tag in an HTML tag you can also use the function the_title_attribute() which will echo a sanitized version of the title. This will prevent things like quotation marks from breaking your layout when using a title in an HTML attribute.

I hope this post cleared up how to get the page title in WordPress using PHP.

If you have any questions about WordPress development let me know in the comments below!

Andy Feliciotti

Andy has been a full time WordPress developer for over 10 years. Through his years of experience has built 100s of sites and learned plenty of tricks along the way. Found this article helpful? Buy Me A Coffee

7 Responses

Hello, Thank you for these explanations.
How can we retrieve the title of a custom_post_type by its ID?
Have a nice day

Just using get_the_title and putting your ID into it like this get_the_title(5313) will grab the title of a custom post type by its ID.

Great it works, thank you very much.
Small question, how can I dynamically retrieve the title ID if I decide to delete it and recreate another one from my plugin? Here is his code:
add_action(‘init’, function () register_post_type(‘titlefooter’, [
‘label’ => ‘Footer titles’,
‘public’ => true,
‘menu_position’ => 3,
‘menu_icon’ => ‘dashicons-ellipsis’,
‘supports’ => [‘title’],
‘show_in_rest’ => true,
‘has_archive’ => true,
]); >);

I believe if the slug is still the same for the post type you’re registering it should act the same. I’m not sure of the question I guess.

No, sorry, that doesn’t work…
I will search again on the web hoping to find a solution for my WordPress theme.
If not, I’ll think of another way to do it.
Thank you again for your help.

Источник

get_the_title() │ WP 0.71

Получает заголовок записи (поста). Можно указать запись заголовок которой нужно получить. Функцию можно использовать внутри Цикла WordPress без указания параметра, тогда будет возвращен заголовок текущей записи в цикле. Или передайте ID поста в первом параметре и функция вернет заголовок указанной записи. Если пост «защищен паролем» или является «личным», то пред заголовком появится соответствующая метка: «Защищен: » (Protected: ) и «Личное: » (Private: ).

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

Используйте функцию the_title_attribute(), когда нужно добавить заголовок записи в атрибут HTML тега.

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

Возвращает

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

$post_title = get_the_title( $post );

$post(число/WP_Post) Идентификатор записи. Можно передать сразу объект записи. По умолчанию: 0 — текущий пост в цикле

Примеры

#1 Выведем заголовок поста 25

echo get_the_title( 25 ); // или можно передать объект $the_post = get_post( 25 ); echo get_the_title( $the_post );

#2 Нужно ли экранировать вывод

Экранирование может быть нужно, когда заголовок выводится в атрибуте тега:

Какую-то общую функцию экранирования можно повесить на хук:

add_filter( ‘the_title’, ‘my_escape_title’ ); function my_escape_title( $title )

#3 Выведем заголовок текущей записи в цикле

echo get_the_title(); // или так в теге H1 echo '

'. get_the_title() .'

';

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

Код get_the_title() get the title WP 6.2.2

function get_the_title( $post = 0 ) < $post = get_post( $post ); $post_title = isset( $post->post_title ) ? $post->post_title : ''; $post_id = isset( $post->ID ) ? $post->ID : 0; if ( ! is_admin() ) < if ( ! empty( $post->post_password ) ) < /* translators: %s: Protected post title. */ $prepend = __( 'Protected: %s' ); /** * Filters the text prepended to the post title for protected posts. * * The filter is only applied on the front end. * * @since 2.8.0 * * @param string $prepend Text displayed before the post title. * Default 'Protected: %s'. * @param WP_Post $post Current post object. */ $protected_title_format = apply_filters( 'protected_title_format', $prepend, $post ); $post_title = sprintf( $protected_title_format, $post_title ); >elseif ( isset( $post->post_status ) && 'private' === $post->post_status ) < /* translators: %s: Private post title. */ $prepend = __( 'Private: %s' ); /** * Filters the text prepended to the post title of private posts. * * The filter is only applied on the front end. * * @since 2.8.0 * * @param string $prepend Text displayed before the post title. * Default 'Private: %s'. * @param WP_Post $post Current post object. */ $private_title_format = apply_filters( 'private_title_format', $prepend, $post ); $post_title = sprintf( $private_title_format, $post_title ); >> /** * Filters the post title. * * @since 0.71 * * @param string $post_title The post title. * @param int $post_id The post ID. */ return apply_filters( 'the_title', $post_title, $post_id ); >

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

title (заголовок)

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

  • 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_content()
  • get_the_date()
  • get_the_excerpt()
  • get_the_ID()
  • get_the_modified_date()
  • get_the_modified_time()
  • get_the_permalink()
  • get_the_time()
  • get_the_title_rss()
  • has_excerpt()
  • post_password_required()
  • register_post_status()
  • the_author()
  • the_content()
  • the_date()
  • the_excerpt()
  • the_excerpt_rss()
  • the_ID()
  • the_modified_date()
  • the_permalink()
  • the_time()

Как задать метаданныйе (тайтл, кейвордс, и десрипшн) для рубрике без плагина? Думаю, это многим интересно.

Здравствуйте Тимур, я бы хотел узнать есть ли какая нибудь функция, что бы получить всё в обратном порядке ? типа:

$pID = get_post_id($title); echo "ID Поста".$pID;

В ответ:
ID Поста: 1 Устал Вытаскивать через query_posts(). Спасибо и Ещё Вопрос, Возможно ли получить все данные по title:

$post_obj = get_page_by_title( 'привет, мир!', OBJECT, 'post' ); $post_id = $post_obj->ID;
($wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s", $post_title ) ))
echo get_post($review)->post_title;

Он выведется таким, каким хранится в базе данных. Правда при выводе лучше использовать esc_html() от греха подальше, читай очистка (валидация, проверка) входящих/исходящих данных в WordPress. Если нужно, чтобы заголовок выводился по принципам самого WordPress, то лучше использовать вариант

echo get_the_title( $review );

Функция get_the_title() проводит ряд проверок (см. её код), а также задействует ряд фильтров, которыми пользуются как сам движок, так и темы/плагины. Главный из них фильтр the_title. На этот фильтр подвязаны ряд функций по очистки строки, делающий заголовок безопасным при выводе на экран. В описании к фильтру в разделе «Где используется хук в ядре WordPress» можно увидеть все функции, подвязанных на этот хук. На мой взгляд в большинстве случаев лучше использовать данный вариант — и читается понятнее и движок все необходимые очистки делает самостоятельно + остаётся возможность темам/плагинам воздействовать на заголовок при необходимости.

Источник

get_the_title()

Возвращает заголовок записи для дальнейшей работы. В параметрах можно указать для какого именно поста выводить заголовок.

К заголовку будет добавлен текст «Защищен:» или «Личное:», если запись защищена паролем или установлена опция Личное.

Функция не выводит на странице заголовок.
Вы можете вывести указав echo get_the_title(); или используйте the_title()

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

Возвращает

строку
Заголовок текущего поста.

Примеры

1. Вывести заголовок записи с ID 5

2. Получить заголовок текущей записи в цикле, заменить 2017 на 2018 и вывести его в теге

' . $title . ''; // выведет 

Популярные игры в 2018 году

?>

Исходный код get_the_title()

Расположен в wp-includes/post-template.php строка 110

function get_the_title( $post = 0 ) < $post = get_post( $post ); $title = isset( $post->post_title ) ? $post->post_title : ''; $id = isset( $post->ID ) ? $post->ID : 0; if ( ! is_admin() ) < if ( ! empty( $post->post_password ) ) < /** * Filters the text prepended to the post title for protected posts. * * The filter is only applied on the front end. * * @since 2.8.0 * * @param string $prepend Text displayed before the post title. * Default 'Protected: %s'. * @param WP_Post $post Current post object. */ $protected_title_format = apply_filters( 'protected_title_format', __( 'Protected: %s' ), $post ); $title = sprintf( $protected_title_format, $title ); >elseif ( isset( $post->post_status ) && 'private' == $post->post_status ) < /** * Filters the text prepended to the post title of private posts. * * The filter is only applied on the front end. * * @since 2.8.0 * * @param string $prepend Text displayed before the post title. * Default 'Private: %s'. * @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 ); >

WordPress сообщество

2016—2023 © WPSchool.ru — Обучающий ресурс о WordPress, статьи, уроки, обучение и курсы.
Размещаемся на лучшем хостинге Beget ❤️ .

Этот сайт использует cookie для хранения данных. Продолжая использовать сайт, Вы даете свое согласие на работу с этими файлами. OK

Источник

Get Webpage Title and Meta Description from URL in PHP

Hi! Today we’ll see how to get webpage title and description from url in php. At times you may want to scrape some url and retrieve the webpage contents. You may need some third-party DOM Parser for this sort of task but PHP is uber-smart and provides you with some fast native solutions. Retrieving page title and meta description tags from url is lot easier than you think. Here we’ll see how to do it.

A Web Page title can be found between the tag and description within tag. Page title is self-explanatory and meta tags store various useful information about a webpage like title, description, keywords, author etc.

php-get-web-page-title-description-from-url

PHP Code to Get Webpage Title from URL:

In order to get/retrieve web page title from url, you have to use function file_get_contents() and regular expression together. Here is the php function to retrieve the contents found between tag.

]*>(.*?)/ims', $page, $match) ? $match[1] : null; return $title; > // get web page title echo 'Title: ' . getTitle('http://www.w3schools.com/php/'); // Output: // Title: PHP 5 Tutorial ?>

PHP Code to Get Webpage Meta Description from URL:

Get/Retrieve meta description from webpage is even more easier with php’s native get_meta_tags() method. The function get_meta_tags() extracts all the meta tag content attributes from any file/url and returns it as an array.

Here is the php function to get the meta description from url.

 // get web page meta description echo 'Meta Description: ' . getDescription('http://www.w3schools.com/php/'); // Output: // Meta Description: Well organized and easy to understand Web bulding tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, and XML. ?>

Some WebPages may miss meta tags and the above function will return null value if it is not present.

Also you can retrieve the rest of the meta tags in the same way.

We have seen how to get webpage title and meta description from url in php. I hope you enjoy this tutorial. If you have any queries please let me know through your comments.

Источник

Читайте также:  Building web application with python
Оцените статью