我试图在Wordpress中创建一个自定义图库,显示第一个图库项目的图像和所有其他项目的文本。
我编写了下面的代码,但这只输出第一个项目,而不输出其他项目。
你知道我做错了什么吗?
$i = 0;
foreach ( $attachments as $id => $attachment ) {
if ($i == 0) {
echo 'the first one';
}
if ( $i !== 0) {
$link = isset($attr['link']) && 'file' == $attr['link'] ? wp_get_attachment_link($id, 0, false, false) : wp_get_attachment_link($id, 0, false, false);
$output .= "<{$itemtag} class='gallery-item'>";
$output .= "
<{$icontag} class='gallery-icon'>
$link
</{$icontag}>";
if ( $captiontag && trim($attachment->post_excerpt) ) {
$output .= "
<{$captiontag} class='wp-caption-text gallery-caption'>
" . wptexturize($attachment->post_excerpt) . "
</{$captiontag}>";
}
$output .= "</{$itemtag}>";
if ( $columns > 0 && ++$i % $columns == 0 )
$output .= '<br style="clear: both" />';
}
$output .= 'Images: ' . count($attachments);
$output .= "
<br style='clear: both;' />
</div>'n";
return $output;
}
$i++;
}
你正在做的是return $output;
——它会让整个过程停止。
尝试echo $output;
代替。否则我认为你已经得到了它。
正如另一个响应所指出的,您也有一些语法错误。例如,在这行缺少左花括号{
:
if ( $columns > 0 && ++$i % $columns == 0 )
您还需要清除$output变量。在每次循环开始时设置$output = '';
,否则您将继续添加$output
并重复结果。
该行缺少左花括号:
if ( $columns > 0 && ++$i % $columns == 0 )
$output .= '<br style="clear: both" />';
那么for循环在$i++
之前结束,$i永远不会递增。
你可以把它作为一个函数使用然后你可以在你的模板中回显这个函数
类似于functions。php
function countimages($id)
{
$i = 0;
$countthem = count($attachments); //count them
foreach ( $attachments as $id => $attachment ) {
if ($i == 0) {
echo 'the first one';
}
if ( $i !== 0) {
$link = isset($attr['link']) && 'file' == $attr['link'] ? wp_get_attachment_link($id, 0, false, false) : wp_get_attachment_link($id, 0, false, false);
$output .= "<{$itemtag} class='gallery-item'>";
$output .= "
<{$icontag} class='gallery-icon'>
$link
</{$icontag}>";
if ( $captiontag && trim($attachment->post_excerpt) ) {
$output .= "
<{$captiontag} class='wp-caption-text gallery-caption'>
" . wptexturize($attachment->post_excerpt) . "
</{$captiontag}>";
}
$output .= "</{$itemtag}>";
if ( $columns > 0 && ++$i % $columns == 0 )
$output .= '<br style="clear: both" />';
}
$output .= 'Images: ' . count($attachments);
$output .= "
<br style='clear: both;' />
</div>'n";
return $output;
}
$i++;
}
}
then echo it inside your template page
$id=the_ID();
echo countimages($id);