Home > Software engineering >  Capitalize HTML title tag
Capitalize HTML title tag

Time:09-09

I am working on a WordPress site that is using Advanced Custom Fields and the HTML title is in one of the field groups and each new page has a page title entered manually and then output with

<title><?php echo the_field('custompagetitle'); ?></title>

For example pages are titled PAGE ONE, PAGE TWO, etc.

I am looking for a way to convert all page titles to Capitalized as in into Page One, Page Two, etc.

I believe the HTML title can not be targeted by css so I have searched here and elsewhere for javascript or other method to achieve this but almost every example I find outputs the to log console or is for other strings and constants but not the page title.

Would appreciate any ideas, thanks

EDIT: This may be due to how ACF processes php because answers posted until this edit don't seem to work. Adding ACF tag as well.

CodePudding user response:

HTML title tags cant be targeted by CSS but you can mainpulate any DOM elements with Javascript like so..

const capitalize=(word)=> {
  return word[0].toUpperCase()   word.slice(1).toLowerCase();
}
let title= document.querySelector('title')
title.textContent=capitalize(title.textContent)

CodePudding user response:

You can try this code it will work. I have tested this code.

<title><?php echo ucwords(strtolower(get_field('custompagetitle'))); ?>

CodePudding user response:

You will need to first lowercase all the words and then convert first letter of each word to uppercase. The following code should work for you:

<?php
$title = get_field('custompagetitle');
$title = ucwords(strtolower($title));
?>
<title><?php echo esc_html($title); ?></title> 
  • Related