【问题标题】:How to properly concatenate string on a function in PHP如何在 PHP 中的函数上正确连接字符串
【发布时间】:2025-12-31 15:05:06
【问题描述】:
function recent_posts_function() {

$call_number = the_field('call_number');
$book_author = the_field('book_author');
$publisher = the_field('publisher');
$edition = the_field('edition');
$description = the_field('description');
$subjects = the_field('subjects');

query_posts(array('post_type' => 'model', 'orderby' => 'date', 'order' => 'ASC' , 'showposts' => 5));   
if (have_posts()) :
  while (have_posts()) : the_post();
        echo
        '<div class="book-list-section">'
            '<h3>' .$call_number '</h3>'                
        '</div>';
    endwhile;
endif;
wp_reset_query();  
}

这是 wordpress,但我的问题是我无法正确连接 html 代码并回显它。请帮助我,我搜索并尝试过但仍然不知道...


function recent_posts_function() {  

 query_posts(array('post_type' => 'model', 'orderby' => 'date', 'order' => 'ASC' , 'showposts' => 5));   
 if (have_posts()) :
    while (have_posts()) : the_post();
        echo 
        '<div class="book-list-section">
            <h3>'.the_field(call_number).'</h3>
            <p><span>'.get_the_title().'</span></p>
            <br  class="clear" />
            <p>' .the_field('book_author').'</p>
            <br class="clear" />
            <p>' .the_field('publisher').'</p>
            <p>' .the_field('edition'). '</p>
            <p>' .the_field('description').'</p>
            <br class="clear" />
            <p>' .the_field('subjects'). '</p>
        </div>';
    endwhile;
 endif;
 wp_reset_query();    
 }

它正在工作,但它不在 div 内......这是为什么呢? "get_the_title()" 只是 DIV 中的那个……这有什么问题?

【问题讨论】:

    标签: php wordpress concatenation


    【解决方案1】:

    您在$call_number 变量之后有一些不必要的引号并错过了连接运算符。

    正确的方法...

    echo '<div class="book-list-section"><h3>'.$call_number.'</h3></div>';
    

    【讨论】:

    • 您的 have_posts() 似乎返回 false,这就是它没有被打印出来的原因。
    • 我直接将 .$call_number 替换为 the_field('call_number') 并打印,但它不在正确的标签中。我在

      标签之外使用了萤火虫。为什么会这样?

    • "1"

      这是结果,请再次帮助...呵呵
    【解决方案2】:

    假设这是 ACF

    the_field()直接回显字段值

    在您的回声块中使用get_field()


    get_field() 也应该在循环内部使用,您在问题外部使用它

    【讨论】:

    • @Ghost,很高兴你得到它的工作伙伴。马克斯感谢您的帮助。 +1
    • 确保在循环中也使用get_field()。 :)