附件只是一篇带有post_status
= inherit
以及post_type
= attachment
, 因此可以使用WP_Query
或get_posts
.
请注意,slug(post_name
) is unique per post type.
$_header = get_posts(\'post_type=attachment&name=book-site-header&posts_per_page=1&post_status=inherit\');
$header = $_header ? array_pop($_header) : null;
$header_url = $header ? wp_get_attachment_url($header->ID) : \'\';
您还可以使用上面的代码构建自己的自定义功能
function get_attachment_url_by_slug( $slug ) {
$args = array(
\'post_type\' => \'attachment\',
\'name\' => sanitize_title($slug),
\'posts_per_page\' => 1,
\'post_status\' => \'inherit\',
);
$_header = get_posts( $args );
$header = $_header ? array_pop($_header) : null;
return $header ? wp_get_attachment_url($header->ID) : \'\';
}
然后
$header_url = get_attachment_url_by_slug(\'book-site-header\');