我正在使用短代码终极灯箱创建查询。但这在常规 php 页面中起作用的唯一方法是将数据保存为字符串。所以我需要做的是创建我的查询,但以某种方式在字符串中获取我的结果。
在我使用任何类型的 php 查询之前,这是有效的:
<?php
$my_tabs = "<ul class='easybuttons'>
<li>[su_lightbox type='inline' src='#lightbox1']AT&T[/su_lightbox]</li>
<li>[su_lightbox type='inline' src='#lightbox2']Sprint[/su_lightbox]</li>
<li>[su_lightbox type='inline' src='#lightbox3']T-Mobile[/su_lightbox]</li>
</ul>";
echo do_shortcode( $my_tabs );
?>
但我需要 ATT、Sprint、T-Mobile 是动态的。请记住,简码只有在字符串中才有效。
那么我怎样才能在这个字符串中做一个 while 循环呢?我尝试使用运算符(operator)但没有用。
$args = array('post_type' => 'services', 'category_name' => $childid, 'order_by' => 'the_title', 'order' => 'ASC');
query_posts($args);
// The Query
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
$my_tabs .= '<ul class="easybuttons">';
while ( $the_query->have_posts() ) {
$the_query->the_post();
$my_tabs .= '<li>[su_lightbox type="inline" src="#lightbox1"]' . get_the_title() . '</li>';
}
$my_tabs .= '</ul>';
}
/* Restore original Post Data */
wp_reset_postdata();
echo do_shortcode( $my_tabs );
?>
更新:
我尝试使用此代码,但它确实有效。什么都没有通过。我没有收到任何错误,但没有显示简码。
<?php
$args = array('post_type' => 'services', 'category_name' => $childid, 'order_by' => 'the_title', 'order' => 'ASC');
// The Query
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
$lid = 1;
$my_tabs .= '<ul class="easybuttons">';
while ( $the_query->have_posts() ) {
$the_query->the_post();
$my_tabs .= '<li>[su_lightbox type="inline" src="#lightbox' . $lid . '"]' . get_the_title() . '</li>';
$lid++;
}
$my_tabs .= '</ul>';
}
echo do_shortcode( $my_tabs );
wp_reset_postdata();
最佳答案
您需要在某处初始化变量 $my_tabs
,例如在 if block 之外,并增加 lightbox id。您不需要调用 query_posts()
。 order_by
应该是 title
,而不是 the_title
。确保 $childid
绝对是 string of the category slug ,不是名称,如果有疑问,请完全删除该参数,看看是否得到任何结果,因为我认为这很可能是主要问题。
$args = array('post_type' => 'services', 'category_name' => $childid, 'order_by' => 'title', 'order' => 'ASC');
// The Query
$the_query = new WP_Query( $args );
$my_tabs = '';
// The Loop
if ( $the_query->have_posts() ) {
$lid = 1;
$my_tabs .= '<ul class="easybuttons">';
while ( $the_query->have_posts() ) {
$the_query->the_post();
$my_tabs .= '<li>[su_lightbox type="inline" src="#lightbox' . $lid . '"]' . get_the_title() . '</li>';
$lid++;
}
$my_tabs .= '</ul>';
}
关于php - 如何在 PHP 字符串中创建 while 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29735920/