我使用下面的代码首先获取帖子的附件(如果它们是Word文档或pdf文件),然后回显所述附件的url。这在页面上的第一篇帖子上非常有效。然而,在随后的每一篇文章上,都会回显相同的附件url,即使该文章没有附件。我怎样才能避免这种情况发生?
$args = array(
\'post_type\' => \'attachment\',
\'post_mime_type\' => array(\'application/doc\',\'application/pdf\'),
\'numberposts\' => 1,
\'post_status\' => null,
\'post_parent\' => $post->ID
);
$attachments = get_posts( $args );
foreach ($attachments as $attachment) {
echo \'<a href="\' . wp_get_attachment_url( $attachment->ID ) . \'">Download Spec Sheet</a>\';
echo \'</div>\';
}
最合适的回答,由SO网友:VicePrez 整理而成
Try this:
<?php
if ( $attachments = get_children( array(
\'post_type\' => \'attachment\',
\'post_mime_type\' => array(\'application/doc\',\'application/pdf\'),
\'numberposts\' => 1,
\'post_status\' => null,
\'post_parent\' => $post->ID
)));
foreach ($attachments as $attachment) {
echo \'<a href="\' . wp_get_attachment_url( $attachment->ID ) . \'">Download Spec Sheet</a>\';
echo \'</div>\';
}
?>