Javascript 如何从未加载的wordpress帖子中检索img src值?

Javascript 如何从未加载的wordpress帖子中检索img src值?,javascript,mysql,css,wordpress,Javascript,Mysql,Css,Wordpress,我在这里要做的基本上是制作一个loop post的div背景图像的背景 伪代码如下所示: if this.post has an img tag { store the img tag's src into a var, then use that img src var as the background-image of the div which holds the permalink to the post } 这有意义吗?我想我必须从WPDB中检索src,但我真的不知道如

我在这里要做的基本上是制作一个loop post的div背景图像的背景

伪代码如下所示:

 if this.post has an img tag {
  store the img tag's src into a var,
  then use that img src var as the background-image of the div which holds the permalink to the post
 }
这有意义吗?我想我必须从WPDB中检索src,但我真的不知道如何不仅从WPDB中获取数据,而且还将其放入一个变量中,然后在div中用作背景图像

我知道,这是一个相当高的要求,对我来说可能是一个很大的学习曲线。但这就是我们正确学习的方式!:)


任何人,请提前感谢。

您可以使用帖子的“特色图片”。首先,通过将其添加到
functions.php
文件来激活Post缩略图:

add_theme_support( 'post-thumbnails' );
然后,您可以使用以下代码检索特征图像:

$image_src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID));
然后将其应用于您的div:

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

如果您使用jQuery,可以在javascript中执行以下操作:

$(document).ready(function(){
  $('img').each(function(){
    var $containingDiv = $(this).parent();
    $containingDiv.css('background-image', 'url(' + $(this).attr('src'));
  });
});
您必须更改
$(this).parent()
以指向应获取背景的实际元素
$(this).parent()
是img元素的父元素

注意:这将处理html文档中的所有图像。您可能希望限制图像选择器中的范围。例如,如果作为图像父级的html元素具有类名“post”,则可以执行以下操作:

$('.post > img').each(function(){
要查找实际需要的内容,您可能需要查看jQuery文档中的选择器:
.

我有一种感觉,那会是那样的!非常感谢您提供的代码片段。我将第一个代码放在functions.php中,第二个放在header中,将样式放在适当的div中,但它似乎不起作用。