2017-03-04 8 views
0

次のコード:PHP: "タイトル" に ')(the_title' を挿入& "altが" 'the_post_thumbnail'(ワードプレス)の属性はできません

<?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() ''との違いに見たいと思うかもしれません。このような複数のワードプレス機能があります。 'get_'で始まる関数は値を返し、値を返さないものは – Andrew

答えて

2

関数the_title()は、というタイトルが表示された時点ですぐに表示されます。他の関数で使用するためにその値を返しません。多くの同様の名前のWordPressの機能と同様に

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

the_title()実際に戻り値をエコーするget_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

関連する問題