add_filter for title

In Wordpress, I added fields for Spanish Content and Spanish Title in posts. I made a filter to switch the content when Spanish is selected. (See below.) This works in the post but is writing every title in the navigation with the current page title. How could this be re-written to avoid this problem?

if($lan=='es'){
	add_filter('the_content','spanish_content');
	add_filter('the_title','spanish_title');
}

function spanish_content($content){
	
	$spanish=get_post_meta(get_the_id(), 'spanish_content');
	$span= $spanish[0];
	if(!$span){
		$span='<p><em>Spanish translation is not available.</em></p>'.$content;
	}
	return $span;

}

function spanish_title($title){

	$spanish=get_post_meta(get_the_id(), 'spanish_title');
	$span= $spanish[0];
	if(strlen($span)<1){
		return $title;
	}
	return $span;

}

Can you show us the code for the template where you are printing out the title. If you are trying to change the title in the top bar, you need to apply that filter to the <title> attribute in the header.php

Thanks for responding. Basically, I’m trying to override the_title() to deliver the Spanish title field. the_title() is used in many instances (blog templates, navigation,etc… ) It would be great if there was a way of making it work in every case because it would be very time consuming to update every place where it is used.

I think the problem hinges on feeding the function the correct ID. Is there a way to distinguish between the current post id and the id of a post in a loop within these functions?

Thank you E

If it is always in the loop you could try something like


function spanish_title($title){ 
    
    global $post;

    $spanish=get_post_meta($post->ID, 'spanish_title'); 
    $span= $spanish[0]; 
    if(strlen($span)<1){ 
        return $title; 
    } 
    return $span; 

}