Question

I am using a static frontpage and a page for my blogposts. In my header.php I want to display the title of the selected page of my blogposts.

For example:

<?php 
if( is_home() )
 echo '<h1>' . get_the_title() . '</h1>';
?><nav> 
... 
</nav>

But of course get_the_title() returns the first element of the displayed posts and not of the page itself.

How can I display the title of the assigned home page?

Était-ce utile?

La solution

You can make use the queried object to return the title of the page used as blogpage

You can use the following: (Require PHP 5.4+)

$title = get_queried_object()->post_title;
var_dump( $title );

Autres conseils

You can get the id from options and then echo the title using that id.

// Blog Page
$page_for_posts_id = get_option( 'page_for_posts' );

echo get_the_title($page_for_posts_id);

// Front Page
$frontpage_id = get_option('page_on_front');

echo get_the_title($frontpage_id);

A note for those thinking of using @pieter's solution on index.php - On index.php, you'll want to check that a static Page is set to show the posts in Setting > Reading. The is_home() conditional does not work on index.php, so you do need to check the option is set:

<?php
// See if "posts page" is set in Settings > Reading
$page_for_posts = get_option( 'page_for_posts' ); 
if ($page_for_posts) { ?>
    <header class="page-header">
        <h1 class="page-title" itemprop="headline">
            <?php echo get_queried_object()->post_title; ?>
        </h1>
    </header>
<?php } ?>

This check is important because index.php is also called when "Front Page Displays > Your latest posts" is set. In that case, get_queried_object()->post_title; will return an object-not-found error.

This works for me

<?php if ( is_home() ) : ?>

    <section class="hero">
<div class="container">
    <div class="row">
        <div class="col-md-12 text-center">

            <h1>news, and personal musings</h1>
        </div>
    </div>
</div>

If it is just about the home page tile, why don't you hard code the title?

<?php if ( is_home() ) : ?>
   <h1>Your blog posts page title</h1>
<?php endif; ?>
Licencié sous: CC-BY-SA avec attribution
Non affilié à wordpress.stackexchange
scroll top