我试图在while循环中调整一行php代码,但我所做的一些事情破坏了它在html中的写入方式。当我在数据库中查询my_product
的值并将其插入div标记之间时,一切都正常,如下所示:
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<div>' . the_field('my_product') . '</div>';
}
但是,当我尝试查询my_colour
并将值作为class
插入第一个div标记时,my_colour
的值会在div标记之前写入html:
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<div class="' . the_field('my_colour') . '"></div>';
}
我在这里做错了什么?(如果你想知道the_field()
,它是Wordpress中高级自定义字段插件的一个函数)
试着先弄清楚变量的类型。这两种方法可能有助于找出的类型
print_r(the_field('my_colour'));
和
echo gettype(the_field('my_colour'));
当您知道变量时,您应该能够将其转换为字符串。
基于馅饼的发现的正确答案:
while ( $the_query->have_posts() ) {
$the_query->the_post();
$colour = get_field('my_colour');
echo '<div class="' . $colour . '"></div>';
}