Get the title

WordPress provides a nice little function for displaying the title of the current post: the_title(). This function gets used all over the place: in the site header, at the top of single posts and pages, in the loop, in the footer, etc. It is probably one of the most commonly used functions by theme developers, and sometimes plugin developers, depending on the plugin. What many developers don’t realize, however, is that there is actually a time that this function should not be used for retrieving and showing a post title, and that is in attributes.

I run into snippets like this a lot:

In general this is fine and displays perfectly fine most of the time. The problem is simple: when outputting the title of a post in an attribute, you should always use the_title_attribute(). The reason comes down to escaping.

Let’s look at the source for the two functions.

the_title()

This one doesn’t show us what we need, since it just calls get_the_title(), so let’s also look at the source for that function:


This function is pretty simple, it retrieves the post object using get_post() and then, after passing it through a filter called the_title, returns $post->post_title.

The important part of this function (to properly illustrate this issue) is the applied filter: apply_filters( ‘the_title’, $title, $id );

This filter can be used by developers to modify the output of the title, perhaps to add extra HTML markup.

the_title_attribute()

This function also uses get_the_title() to retrieve the title of the post, but the final data that is returned is different from the_title(), primarily in that it is escaped. What does this mean? It means that it is safe to use inside of element attributes. It also strips all tags.

Let’s look at an example.

Assume your $post->post_title is this:

When outputted with the_title(), this will remain completely unchanged and will display as:

But when you output this title through the_title_attribute(), you get this:

Notice that the span tags have been removed.

What if your title had quotation marks in it? Such as:

With the_title(), the title will be outputted as:

With the_title_attribute(), the title will be outputted as:


Notice how the quotation marks have been converted to entities?. This is called escaping and it ensures that attributes, such as title=”the title here”, don’t end up getting closed too early.

If we use the_title() inside of an attribute and the title has quotation marks, we will end up with broken markup.

Results in:

Notice that the title attribute gets closed with the first ” around the word quotation. This results in completely broken markup that might look something like this:

Screen Shot 2013-07-11 at 10.23.18 AM

In order to not break the markup, you should always use the_title_attribute() when showing the title of a post inside of an attribute. It’s a very appropriately named function.

The usage of the_title() in attribute tags has actually caused my huge headaches with Easy Digital Downloads. We use the the_title filter to add Schema.org micro data to products, which is excellent because the data is used by search engines to enhance search result entries with product data (price, rating, etc). The problem is that we get at least one support ticket every week from a user that has broken HTML markup (like that pictured above). The problem is prevalent enough that we are being forced to add an option to disable our schema.org micro data.


If you care about better compatibility with plugins, and simply doing the right thing, you should update any theme or plugin that uses the_title() incorrectly. Note, WordPress core itself has a similar problem as well, so it’s not just themes and plugins.

pippinsplugins.com

Есть ли способ всегда, чтобы the_title() также включал настраиваемое поле под названием субтитры?

Я хочу иметь такой заголовок: « subtitle-custom-field: Post Title ». Например, « Круто: новое телешоу от Вернера Херцога ».


  • Как очистить заголовок сообщения запятыми
  • WP action / filter для изменения заголовка перед выходом заголовка и вывода статьи?
  • Заголовок длинного сообщения Misaligning Grid с избранным изображением
  • Как добавить hook в the_title () и get_the_title ()
  • посты по названию второе слово
  • get_posts () возвращает один и тот же файл the_title () для каждого сообщения

В этом случае cool будет настраиваемым значением поля, а новым ТВ … будет the_title() .

Я получаю это в настоящий момент со следующим кодом:

 <h1><?php $values = get_post_custom_values("myCustomField"); echo $values[0]; ?>: <?php the_title(); ?>"><?php $values = get_post_custom_values("myCustomField"); echo $values[0]; ?> <p><?php the_title(); ?></p></h1> 

Проблем.
x430; без него, что в некоторых случаях не имеет смысла. Я также дал все возможные « теги заголовков » полный заголовок таким же образом в атрибуте title= .

Есть ли способ сказать WordPress, если есть специальный подтекст поля, всегда печатать его перед post_title
?

Solutions Collecting From Web of «настраиваемое поле всегда для .get_the_title ()?»

www.wordpressask.com

Sometimes we want to get current page title, which is displayed in <title> tag. Here I mean the page in general meaning, not WordPress “page”. We have several WordPress functions that can help such as:

  • get_the_title(): to get current post/page/any post type title
  • single_cat_title(): to get current category title. There’re sibling functions for tags and terms as well: single_tag_title() and single_term_title()
  • get_bloginfo(): to get the blog name
  • etc.

Using those functions are great, but they have some disadvantages:

  • Those functions are specific for particular pages like single post/page, category/tag, … pages. But we can have many page types in WordPress like: 404 page, search result page, archive page, or even virtual page.

  • The title displayed differently in themes: you may use a theme that have title in format Post Title | Blog Name, but another theme can use Post Title only. You can make a combination of the functions above to achieve the correct title, but that won’t be used widely for other themes.
  • Or you might set the title in various ways with SEO plugins

In this post, I’m gonna to use a simple trick that can solve these problems quickly.

I’m sure all of us are familiar with function wp_title(), we often use this function in header.php file, like this:

<title><?php wp_title( '|', true, 'right' ); ?></title> 

to display the page title (you should use only this function to display page title, otherwise your site maybe not compatible with SEO plugins or causes performance issue).

The trick is switch the 2nd parameter $echo from true to false to get the value of current page title:

$title = wp_title( '|', false, 'right' ); 

Here is an example where this technique is useful. We’re going to display a Twitter button. I’m gonna to use another cool technique from Konstantin Kovshenin to get the current page URL:

   
global $wp; $link = add_query_arg( $wp->query_string, '', home_url( $wp->request ) ); $text = wp_title( '|', false ); printf( '<iframe allowtransparency="true" frameborder="0" scrolling="no" src="https://platform.twitter.com/widgets/tweet_button.html?url=%s&text=%s&count=horizontal"></iframe>', urlencode( $link ), rawurlencode( $text ) );

I’m currently use the script above (with some additions for facebook like, google+ buttons) for my websites. And it’s working great in archive pages where built in WordPress functions aren’t very helpful.

deluxeblogtips.com

This little tidbit is for all you WordPress themers out there.  It is important that your theme displays the proper title on the page no matter what settings a user has on their site.  As you probably are already aware, a user can go to ‘Settings’ -> ‘Reading’ in the WordPress admin menu and change what pages are used for the front page and the posts page (aka blog page)…

Get the title

So in the example above, I want to set a static page as my homepage and delegate another page to host my blog (aka posts page).  So now that my posts page is no longer the front page, I want to display the page title that the user assigned to that page in my theme.  This helps add clarity for users and makes all of my pages have a more consistent appearance.  As an example, it could be that I am using the posts page for displaying news items and want to label my posts page ‘News’.


Rather than leaving it up to the user to go in and try to hack your theme to get the page title to appear, you decide you want to display this page title for them automatically.

WordPress provides you with the functionthe_title(), which works great inside the loop.  Problem is, you are using that inside the loop to display the title for all of your blog entries on the page and that won’t do you any good when trying to fetch the page title outside the loop.  If you try to use this function for the page title outside the loop, all you get is the title of the first post on the page.

So how do we fetch the page title for our posts page?

There are two ways to do it.  First is the easy way:

single_post_title();

The only problem you might encounter with this method is that the function echoes our title immediately.  If you want to get the title as a variable for any reason, you would have to use output buffering to do it.

You can use the functionget_the_title() to get the title of a page as a variable just by providing the ID.  If you don’t provide an ID, then the function will try to fetch the ID for the current page.  Unfortunately, this function doesn’t detect the current page ID properly in our use case, which is why using functionthe_title() didn’t work for us earlier:  the_title() is just a wrapper function for get_the_title().

Luckily for us, WordPress does store the ID of the page you want to use for the posts page in the database.  So we can fetch the title as a variable, like this:

$our_title = get_the_title( get_option('page_for_posts', true) );

This may be more than you ever needed to know about fetching the title for an assigned posts page, but now you know! 😉

wpscholar.com


You May Also Like

About the Author: admind

Добавить комментарий

Ваш e-mail не будет опубликован. Обязательные поля помечены *

Этот сайт использует Akismet для борьбы со спамом. Узнайте как обрабатываются ваши данные комментариев.

Adblock
detector