-2

I have a WP site, every page have a heading H1 acting as a title, right that code change the that heading like this, if the page is services post that if not post the title of tha page, but I want to post a different title that the name of the page.

Here is my code:

    <h1 style="background: #000;
     color:#FFF;
     margin-bottom:10px;
     padding:8px 12px;
     box-sizing:border-box;
     text-transform: uppercase;
     font-size: 16px;">

     <?php if (is_page('services')) {
      ?>SERVICES<?php 
       } else { 
        the_title();
       }
      ?>

</h1>
Poorna Senani Gamage
  • 1,246
  • 2
  • 19
  • 30
crjo
  • 1

1 Answers1

0

So many things to address:

  1. Don't use inline styles. That is bad form. Assign a CSS class, and add the CSS to your stylesheet.
  2. Format your code. Never-ending blocks of code are impossible to read, diagnose, and troubleshoot.
  3. Doing it this way is going to lead to a big mess of conditional if statements. is_page is only going to handle one override for you at a time, AND it's brittle - if the page slug / title changes, this function will no longer pick it up. I'd strongly recommend getting and using something like Advanced Custom Fields and allow setting the "Display Title" that way. It'd be much easier to code, maintain, etc.

Lastly - using what little you've given us, here is your code restructured into a much more readable, usable, and functioning solution:

<?php
// Load the title into a variable for simpler manipulation / logic
$title = get_the_title();
// If the page is the 'services' slug page, set the title
if ( is_page('services') ) {
   $title = 'Services';
}

// other conditions can go here, if you like
if ( is_page('contact' ) {
   $title = 'Contact Us';
}
?>

<h1 class="page-title"><?php echo $title; ?></h1>
random_user_name
  • 25,694
  • 7
  • 76
  • 115
  • Thank you so much @cale_b if oe on my pages is in a sub tree like this www.somethin.com/services/somethingelse should I use the is page fucnction like this ` if ( is_page ('services/somethingelse')` or just the name of that page? thank you so much – crjo Mar 05 '18 at 19:42
  • Just the name of the page. _Better_ would be the ID of the page, eg `is_page(21)`.... – random_user_name Mar 05 '18 at 19:57
  • Im getting a error on this line if ( is_page('mock-trial' ) – crjo Mar 05 '18 at 20:09
  • That wasn't part of the original question. If my answer helped you, then great! If you're trying to add new code, and having a hard time, then you need to ask a new question. (Also, if my answer helped, please consider clicking the "upvote" button - the big arrow to the left, just above the number) – random_user_name Mar 05 '18 at 20:30