2017-03-04 32 views
0

以下代碼:PHP:不能在 「標題」 插入 'the_title()' & 「ALT」 屬性在 'the_post_thumbnail'(WordPress的)

<?php if (has_post_thumbnail()) : ?> 
    <?php $attr = 'Is ' . the_title() . ' a good computer?'; ?> 
    <p><?php the_post_thumbnail('medium', ['title' => $attr, 'alt' => $attr]); ?></p> 
<?php endif; ?> 

產生輸出:

<p><img width="300" height="300" src="http://www.example.com/wp-content/uploads/2016/04/image.jpg" alt="Is a good computer?" title="Is a good computer?" ></p> 

爲什麼不包含the_title()

幫助讚賞。

+2

你可能想看看the_title()'和'get_the_title()''之間的差異。有這樣的多個wordpress功能;以'get_'爲前綴的函數返回一個值,沒有它的函數將返回值 – Andrew

回答

2

函數the_title()打印標題立即被調用時,它不會返回其值用於其他函數。使用get_the_title()相反,它返回它的值:

<?php if (has_post_thumbnail()) : ?> 
    <?php $attr = 'Is ' . get_the_title() . ' a good computer?'; ?> 
    <p><?php the_post_thumbnail('medium', ['title' => $attr, 'alt' => $attr]); ?></p> 
<?php endif; ?> 

像許多類似命名的WordPress的功能,the_title()實際上調用get_the_title()呼應的返回值。 From documentation

function the_title($before = '', $after = '', $echo = true) { 
    $title = get_the_title(); 
    if (strlen($title) == 0) 
     return; 
    $title = $before . $title . $after; 
    if ($echo) 
     echo $title; 
    else 
     return $title; 
} 

WordPress的文檔:

the_title() function

get_the_title() function

+0

好人,謝謝Dzmitry – Steve

相關問題