I'm trying to modify the WordPress page title. However I'm fairly new to WordPress functions, hooks (filters & actions) and so on.
What I could achieve is to change and modify WordPress titles in the <body>
. I also was able to change to Page title (<head>
), but not to modify it. E.g.:
Original page title:
My house is red
Modified page title (| -> is used for seperate examples):
My house is green | My house is red and blue
So I want to add or remove specific characters or numbers/integers of my page title. To be clear what I exactly try to achieve is:
I want to hook the original page title of my (custom post types) pages and "filter" the first three numbers of my title.
My titles of my custom post types are numbered and look like:
- 000 Main Category X
- 100 Sub Category X
- 101 Sub Category 01 X
- 200 Sub Category Y
- ... and so on
I changed the titles for WordPress, so my custom post types are sorted correctly for the back/forward navigation. The module I used isn't able to sort the custom post types on its own.
So I don't want any numbers (always three numbers) in front of my page titles. I planned to "filter" them out by using (one of these php functions):
- $x = ltrim($x, 'example123');
- $b = substr($a, 3);
As far I know these filter hooks are achieve:
- pre_get_document_title
- document_title_separator
- document_title_parts
Furter I used these WordPress functions/filter hooks:
function change_page_title( $title ) {
return $title;
}
add_filter( 'pre_get_document_title', 'change_page_title' );
and
function change_page_title( $title ) {
$title['title'] = 'Changed title';
}
add_filter( 'document_title_parts', 'change_page_title' );
+++
So I'm sorry if there might be already a solution for my problem, but I couldn't find any and I'm at the moment not able to solve if on my own. Therefore I hope you might be able to help me. Also you if you have a good recommendation to get better in WordPress development (ressources like videos, courses etc.) I would appreciate it. I do know HTML, CSS, JS and also basic understanding in programming and PHP.
+++
I tried modifying the functions above, like that (and much more, but it didn't work):
function change_page_title( $title ) {
return $title; // works as expected
// return ' test'; // works as expected
// return $title . ' new title'; // doesn't work
// $new = $title;
// $new2 = $title . ' test2';
// return $new; // seem also to work
// return $new2; // doesn't work
}
add_filter( 'pre_get_document_title', 'change_page_title' );
So these were some things I tried to get it working, or rather to test if I'm able to modify the title. I'm sure there is a simple solution and I'm making some sort of stupid mistake.
Thank you for your time.
null
comes out. There's no point changing$title['title']
if you don't return it!