Sorry if my question was basic or stupid but please help me to solve this issue. I’m trying to change <title>
and <meta name="description" >
tags dynamically in wordpress. so this is what I tried in function.php file.
function changeMeta_2(){
global $wpdb;
$cur_url = $_SERVER['REQUEST_URI'];
$basename = pathinfo($cur_url);
$ebasename = $basename['filename'];
if(is_numeric($ebasename)) {
$url = explode('/', $basename['dirname']);
$basename = explode('.', $url[count($url)-2]);
$ebasename = $basename[0];
}
$pageName = $ebasename;
$arraylist_subcat = array("car","bike","boat","xxxx","yyyy","zzz","mmmm");
$arraylist_maincat = array("aus","ind","usa","uae");
$category_id = get_term_by('slug',$pageName, 'category');
$category_parentid = get_term_by('id', $category_id->parent, 'category');
$parent_slug = $category_parentid->slug;
if ( is_page()) {
if ( in_array($pageName,$arraylist_maincat) ) {
$metaTitle = 'Browse '.$pageName.' | Some txt title | mysite.com';
$metaDescription = 'some of custome blablaaaaa text description '.$pageName.' some of custome blablaaaaa text description ';
echo '<title>'.$metaTitle.'</title>';
echo '<meta name="description" content="'.$metaDescription.'"/>';
}
}
}
add_action( 'wp_head', 'changeMeta_2' );
In the above code I’m trying to change the title tag and meta description for term id which are matching with array values (in_array condition).
Everything works fine, but problem is instead of override(replace) <title>
tag is appending in head. Its not changing it appending. please someone help me to solve this issue.
How document title is generated has changed since WordPress v4.4.0. Now
wp_get_document_title
dictates how title is generated:Here is the code from v5.4.2. Here are the filters you can use to manipulate title tag:
So here are two ways you can do it.
First one uses
pre_get_document_title
filter which short-circuits the title generation and hence more performant if you are not going make changes on current title:Second way uses
document_title_separator
anddocument_title_parts
hooks for the title and the title seperator that are executed later in the function, after title is generated using functions likesingle_term_title
orpost_type_archive_title
depending on the page and about to be outputted:For anybody coming to this question in the future: This functionality can be accomplished using the Yoast SEO plugin.
However, if you do want to still do this yourself….
In order to modify the title, rather than the
wp_head
hook, you need to be using the filters that actually allow you to modify the title: wp_titleAnd you can / should use the
wp_head
in order to add the meta description (see the docs here: http://codex.wordpress.org/Meta_Tags_in_WordPress)Also note there’s easier ways to get the page title, mentioned below…
For the title, your code would look something like so: