Display page title instead of post title on search.php and archive.php

I’m working on a WordPress starter theme for future projects. What I want to achieve is to display the title of page search.php and archive.php.

Instead it now shows the title of the latest post. I have googled for hours and read many solutions but with no luck, and it’s really driving me crazy.

Read More

Underneath here you can see I’m looking for search.php and archive.php. But no matter what I try for those pages always display the else statement with ‘this is not search.php or archive.php’.

So in short terms, the search.php and archive.php always display the most recent post title instead of the page title and my elseif statements just get ignored.

Here’s my code, it resides in the header.php thus is outside the loop:

 <?php if ( is_page_template('page.php') ) { ?>

   <h1><?php wp_title(); ?></h1>
   <span class="title-sub"><?php the_field('page_slogan'); ?></span>

 <?php } else if ( is_page_template('search.php') ) { ?>

    <h1><?php wp_title(); ?></h1>


 <?php } else if ( is_page_template('archive.php') ) { ?>

    <h1><?php wp_title(); ?></h1>


 <?php } else { ?>

    <h1><?php the_title(); ?> this is not search.php or archive.php</h1>
    <span class="title-sub"><?php the_field('page_slogan'); ?></span>

 <?php } ?>

How to solve this?


EDIT!!!

Big thanks to Michal S for helping me out here!
The code which I needed turned out to be really simple:

 <?php
   if (is_search()) {
      /* Main title */
      echo '<h1>Search</h1>';
      /* Streamer underneath the main title */
      echo '<span class="title-sub">Found what you were looking for?</span>';
 } else {
      /* Main title */
      echo '<h1>';
      wp_title('');
      echo '</h1>';
      /* Streamer underneath the main title */
      echo '<span class="title-sub">';
      the_field('page_slogan');
      echo '</span>';
      }
 ?>

Related posts

Leave a Reply

1 comment

  1. Use this as a good starting point. You can easily modify or at least use conditions from code below (credits goes to many popular blank templates, author unknown)

    <title>
           <?php
              if (function_exists('is_tag') && is_tag()) {
                 single_tag_title("Tag Archive for &quot;"); echo '&quot; - '; }
              elseif (is_archive()) {
                 wp_title(''); echo ' '; }
              elseif (is_search()) {
                 echo 'Search for &quot;'.wp_specialchars($s).'&quot; - '; }
              elseif (!(is_404()) && (is_single()) || (is_page())) {
                 wp_title(''); echo ' - '; }
              elseif (is_404()) {
                 echo 'Not Found - '; }
              if (is_home()) {
                 bloginfo('name'); echo ' - '; bloginfo('description'); }
              else {
                  bloginfo('name'); }
              if ($paged>1) {
                 echo ' - page '. $paged; }
           ?>
    </title>