您可以使用get\\u posts函数检查给定帖子的附件是否存在。这将创建一个新的sql查询,因此可能存在性能问题。
// Util.class.php
class Util {
public static function has_attachments() {
$args = array(
\'post_type\' => \'attachment\',
\'numberposts\' => -1,
\'post_status\' => null,
\'post_parent\' => $post->ID
);
$attachments = get_posts($args);
if(!empty($attachments)) {
return TRUE;
} else {
return FALSE;
}
}
}
// In template
require_once \'Util.class.php\';
if (Util::has_attachments()) {
// Display gallery
}