Archived topic
Overwriting Page Titles (for SEO) Without and SEO Plugin
13 replies · Started by Martin on May 29, 2020
Hi there.
I am trying to make my titles more SEO friendly and want to use a but of custom code to generate my titles from a custom field rather than have 'Page Title - Site Name' in the browser & Google. In many themes I can do this by editing the header.php (in a child theme, of course) but I cannot find a way to do this with GPP.
I do not wish to install Yoast or any other potentially bloated plugins.
Thanks.
Martin
Hi there,
what are you trying to do ? If it is to change the post title in the <title> tag then you could use the document_title_parts filter like this:
add_filter( 'document_title_parts', 'custom_field_title_tag');
function custom_field_title_tag( $title ) {
// check is a post or page
if ( ! is_singular() )
return $title;
// Get and check for custom field
$custom_title = trim(get_post_meta( get_the_id(), 'your_custom_field_name', true ));
if( ! empty( $custom_title ) ){
$custom_title = esc_html( $custom_title );
$title['title'] = $custom_title;
$title['site'] = '';
}
return $title;
}
I think we're on the same page.
Using a custom field for 'title' is exactly where I was heading...
Martin
Awesome - glad to hear that
Is that code included in GP?
Add the code to your child theme functions.php or code snippets.
Change where it says your_custom_field_name to match your custom field and thats it
I have done the custom function but my titles are still getting the site name appended.
I'm trying to not have the site name appended when I use a custom page title.
Edited the code above to remove the Site Title
Just like that... Wow. A teeny bit extra did the job!
Thank you.
You're welcome.
For reference:
https://developer.wordpress.org/reference/hooks/document_title_parts/
Hi,
It works for page title. How would I be able to insert custom page description?
This is what I did on my website to get a custom description:
/** Custom code to use the Description field for Description Meta Tag */
/*Display custom meta description or the post excerpt */
function add_custom_meta_des(){
#Homepage Meta Description
if( is_home() || is_front_page() ){
$meta_des = "ADD THE HOME PAGE DESCRIPTION HERE"; #Edit here
echo '<meta name="description" content="' . $meta_des . '" />';
}
#Single Page Meta Description
if(is_single() || is_page()){
$des = get_post_meta( get_the_id(), 'Description', true);
if( ! empty( $des ) ){
$meta_des = esc_html($des);
echo '<meta name="description" content="' . $meta_des . '" />';
}
}}
add_action( 'wp_head', 'add_custom_meta_des', 4 );
Thanks for Martin
Thank you Martin. Awesome!