2016-10-03 104 views
0

我正在尋找一種方法來更改WordPress的屏幕上顯示帖子標題的方式,該方式僅適用於帖子標題。WordPress自定義帖子標題

我想在帖子標題中顯示姓名,性別,年齡。我顯示的名稱是當前的帖子標題,我正在嘗試將性別和年齡添加到此目的中,僅用於顯示目的。

我已經使用了當前的代碼,但它適用於我的主題中使用該貼圖的所有內容,並將這些字段添加到菜單項中。 我沒有修改任何PHP文件的主題範圍內,並且想避免這一點,通過功能

這裏做到這一點是我的代碼:

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; 

}); 

我在做什麼它將取代所有這些附加字段標題,而不僅僅是後頭部

回答

0
<?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; 
} 
?> 
+0

這一個工作,看起來像我錯過了檢查的帖子ID! –

1

修訂

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); 

這段代碼在你的活動子主題(或主題)的function.php文件中,或者也在任何插件文件中。

請注意:此代碼未經測試,但它應該工作。


參考:

+0

這一個沒有工作,在我的主題菜單項將不再呈現。 –

+0

@BrettCanfield:我已經更新了我的代碼,檢查這個,它會工作。 –