2017-03-04 33 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

相关问题