Reputation: 71
I am looking for a method to change how a post title is shown on screen in WordPress that only applies to the post header.
I am trying to display Name, Gender, Age in the post title. The name I display is the current post title, and I am trying to add gender and age to this for display purposes only.
I have used the current code, but it applies to everything in my theme that uses the tile, and adds these fields to menu items as well. I have not edited any of the PHP files within the theme, and would like to avoid that and do it via a function
Here is my code:
add_filter( 'the_title', function( $title ) {
$gender = get_field('gender');
$dob = get_field('date_of_birth');
$birthday = new DateTime($dob);
$interval = $birthday->diff(new DateTime);
if ('babysitters' == get_post_type()) {
$temp_title = $title;
$bbstitle = $temp_title .', ' .$gender .', ' .$interval->y;
return $bbstitle;
}
return $title;
} );
What am I doing where it replaces all titles with these appended fields, and not just the post header
Upvotes: 0
Views: 121
Reputation: 10809
UPDATED
function text_domain_custom_title($title) {
global $post;
if ($post->post_type == 'babysitters') {
$gender = get_field('gender', $post->ID);
$dob = get_field('date_of_birth', $post->ID);
$birthday = new DateTime($dob);
$interval = $birthday->diff(new DateTime);
$bbstitle = $title . ', ' . $gender . ', ' . $interval->y;
return $bbstitle;
} else {
return $title;
}
}
add_filter('the_title', 'text_domain_custom_title', 10, 2);
This code goes in function.php file of your active child theme (or theme) or also in any plugin file.
Please note: This code is not tested, but it should work.
Reference:
Upvotes: 1
Reputation: 2436
<?php
add_filter('the_title', 'new_title', 10, 2);
function new_title($title, $id) {
if('babysitters' == get_post_type($id)){
$gender = get_field('gender');
$dob = get_field('date_of_birth');
$birthday = new DateTime($dob);
$interval = $birthday->diff(new DateTime);
$newtitle = $title .', ' .$gender .', ' .$interval->y;
}
else{
$newtitle = $title;
}
return $newtitle;
}
?>
Upvotes: 0