Reputation: 11
i want to make a custom background image, witch will be changed every day, with url to original source. for example :
img name 346.jpg
$dayofyear = date('z');
$dayofyear = Get image by name in wp?
background-image: url(<? php echo $dayofyear; ?>)
thx, and sorry for my English :D
Upvotes: 1
Views: 3154
Reputation: 183
Each image you upload to the media library uses the filename before the extension as it's slug. You can use the get_posts function and pass in $dayofyear:
function get_attachment_url_by_slug( $slug ) {
$args = array(
'post_type' => 'attachment',
'name' => sanitize_title($slug),
'posts_per_page' => 1,
'post_status' => 'inherit',
);
$_background = get_posts( $args );
$background = $_background ? array_pop($_background) : null;
return $background ? wp_get_attachment_url($background->ID) : '';
}
That will return the ID of the image you're trying to get by it's slug.
If you're doing this inside a page or post template, you would use:
$dayofyear = date('z');
$background_url = get_attachment_url_by_slug($dayofyear);
Then set the inline style of the element, for example:
<div style="background-image: url(<? php echo $background_url; ?>);"></div>
This won't work if you're trying to inject this into a stylesheet.
Upvotes: 3