为什么在WordPress中忽略了PHP代码的顺序


Why is the order of PHP code ignored in WordPress?

我是PHP的新手,我想创建一个显示最新帖子缩略图和帖子标题的代码。标题和图片都应该在<a href="#">中,这样人们就可以通过点击图片来查看文章。但当我运行以下PHP代码时,代码会像这样打印出来:

<img width="462" height="260" src="http://vocaloid.de/wp-content/uploads/2014/11/1920x1080_PC_a.jpg" class="attachment-735x260 wp-post-image" alt="1920x1080_PC_a"><a href="http://vocaloid.de/news/test-nr-2/"><h2>HATSUNE MIKU: PROJECT DIVA F EXTEND ANGEKÜNDG</h2></a>

这是我使用的原始代码:

<?php
    $args = array('numberposts' => '1' );
    $recent_posts = wp_get_recent_posts( $args );
    foreach( $recent_posts as $recent ){
        echo '<a href="' . get_permalink($recent["ID"]) . '">' . the_post_thumbnail($recent['ID'], array(735,260)); the_title( '<h2>', '</h2>' ); '</a>';
    }
?>

试试这个:

$args = array('numberposts' => '1' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
    echo '<a href="' . get_permalink($recent["ID"]) . '">';
    the_post_thumbnail($recent['ID'], array(735,260));
    echo the_title( '<h2>', '</h2>' ).'</a>';
}

让我知道输出。

Rohil_PHP初学者的答案是正确的,但我认为它不能解释为什么会发生这种情况。

在使用the_post_thumbnail()的情况下,它会回显结果而不返回。正是因为这个原因,当你试图将其连接成字符串时,它出现在错误的位置。

如果你想获得帖子缩略图,你可以使用get_the_post_thumbnail()

因此,使用get_the_post_thumbnail(),您的代码片段将最终看起来像:

<?php
    $args = array('numberposts' => '1' );
    $recent_posts = wp_get_recent_posts( $args );
    foreach( $recent_posts as $recent ){
        echo '<a href="' . get_permalink($recent["ID"]) . '">'
             . get_the_post_thumbnail($recent['ID'], array(735,260))
             . the_title( '<h2>', '</h2>' )
             . '</a>';
    }
?>

我希望这能进一步澄清。