【问题标题】:How to retrieve an img src value from an un-loaded wordpress post?如何从未加载的 wordpress 帖子中检索 img src 值?
【发布时间】:2013-01-09 23:48:07
【问题描述】:

我在这里要做的基本上是制作循环帖子的 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 中获取该数据,而且将其放入一个 var 中,然后可以在 div 中使用背景图片...

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

提前谢谢大家。

【问题讨论】:

    标签: javascript mysql css wordpress


    【解决方案1】:

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

    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; ?>);">
    

    【讨论】:

    • 我有一种感觉,它会是这样的!也非常感谢代码 sn-ps。我将您的第一个代码放入functions.php,第二个放入标题中,并将样式放入适当的div,但它似乎不起作用。
    【解决方案2】:

    如果你使用 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 文档: http://api.jquery.com/category/selectors/.

    【讨论】:

      猜你喜欢
      • 2021-07-02
      • 1970-01-01
      • 2013-08-06
      • 1970-01-01
      • 2019-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多