Search code examples
phpwordpresswordpress-themingblogs

Home.php using for blog content can't retrieve page title - Wordpress


Hi I want to do the blog part in my wordpress theme, I set up using static front page et blog page to display latest post.

So in my home.php I have :

<?php get_header(); ?>
<section class="header--page">
    <div class="header--img">
        <?php the_post_thumbnail() ?>
    </div>
    <div class="container">
        <h1><?php the_title() ?></h1>
    </div>
</section>
<?php get_footer(); ?>

But instead of getting title from page and featured image from page, It display those from the first posts, any idea ?

I try on my page.php and front-page.php, both are returning correct title and image


Solution

  • So things like the Posts page function a little differently than a standard page. Most likely, your the_title() function is returning the title of the first post to be displayed.

    What you'll need to do is this instead:

    <h1><?php echo get_the_title(get_option('page_for_posts')) ?></h1>
    

    What needs to happen is you need to grab the ID of the Posts page, and use that ID to find its title.

    So you'll want to use get_the_title() instead, because the_title() doesn't allow you to pass an ID of a page or post. get_the_title() accepts an ID as a parameter.

    The page's ID that you specified as your Posts Page in the WP Settings > Reading can be grabbed by using get_option('page_for_posts').

    So putting it all together, the code snippet above will get the title of the Posts Page, and echo it on-screen. (get_the_title() doesn't automatically echo it's returned value like the_title() does, hence the addition of the echo.