我想制作一个自定义的背景图片,女巫每天都会更改,并带有原始来源的网址。
例如 :

img name 346.jpg
$dayofyear = date('z');
$dayofyear = Get image by name in wp?
background-image: url(<? php echo $dayofyear; ?>)


thx,对不起我的英语:D

最佳答案

上载到媒体库的每个图像都使用扩展名之前的文件名,因为它很麻烦。
您可以使用get_posts函数并传入$ 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) : '';
}


这将返回您试图通过它获取的图像的ID。

如果要在页面或帖子模板中执行此操作,则可以使用:

$dayofyear = date('z');
$background_url = get_attachment_url_by_slug($dayofyear);


然后设置元素的内联样式,例如:

<div style="background-image: url(<? php echo $background_url; ?>);"></div>


如果您试图将其注入样式表,则此方法将无效。

08-19 03:45