Sure, we can modify meta tags in WordPress using actions and filters.
The <title>
tag is pretty easy, WP already has a filter called document_title_parts
that allows you to manipulate the title before being outputted to the page. Here's a simplified example of using it :
add_filter( 'document_title_parts', 'filter_document_title_parts', 10, 1 );
function filter_document_title_parts( $title_parts ) {
// Trims the title to a maximum of 60 characters
$max = 60;
if ( strlen( $title_parts['title'] ) > $max ) {
$title_parts['title'] = substr( $title_parts['title'], 0, $max ) . '...';
}
return $title_parts;
}
The meta description tag can be a bit more complex because WordPress doesn't have a functionality for meta descriptions, so if you have them you're most likely using a plugin. Yoast SEO and All In One are the most popular, so I'll give examples for them, they should cover most people.
Yoast SEO :
add_filter( 'wpseo_metadesc', 'filter_wpseo_metadesc', 10, 1 );
function filter_wpseo_metadesc( $metadesc ) {
$max = 155;
if ( strlen( $metadesc ) > $max ) {
$metadesc = substr( $metadesc, 0, $max ) . '...';
}
return $metadesc;
}
All In One SEO :
add_filter( 'aioseop_description', 'filter_aioseop_description', 10, 1 );
function filter_aioseop_description( $description ) {
$max = 155;
if ( strlen( $description ) > $max) {
$description = substr( $description, 0, $max) . '...';
}
return $description;
}
Same thing like the title - we just get the metadescription before the page is rendered and we manipulate them. You can modify the $max variable as you like.
Are there other metas you'd like modified? We can find a hook for them.