【问题标题】:php - get image urls from wordpress postsphp - 从 wordpress 帖子中获取图片网址
【发布时间】:2013-07-27 02:22:24
【问题描述】:

我有基于 wordpress 系统的网站,我需要从每个帖子中获取图片网址。我有这个代码并且它正在工作,但是有问题,因为所有帖子都有相同的图片+在最后,有新的。这是一个例子:

post1 - image1.png,image2.png,image3.png

post2 - image1.png,image2.png,image3.png,new1.png,new2.png

post3 - image1.png,image2.png,image3.png,new1.png,new2.png,third.png

等等……

这是我的 php 代码

preg_match_all('/<img[^>]+>/i',$old_content, $imgTags); 

for ($i = 0; $i < count($imgTags[0]); $i++) {

  // get the source string
  preg_match('/src="([^"]+)/i',$imgTags[0][$i], $imgage);

  // remove opening 'src=' tag, can`t get the regex right
  $origImageSrc[] = str_ireplace( 'src="', '',  $imgage[0]);
}

任何想法,为什么这样做? :-)

【问题讨论】:

  • 你可以通过函数

标签: php image wordpress url


【解决方案1】:

这可能会对您有所帮助,这里有一个函数,您可以将其放入 Wordpress 主题中的 functions.php 文件中。

/*
 * Retreive url's for image attachments from a post
 */

function getPostImages($size = 'full'){
    global $post;
    $urls = array();

    $images = get_children(array(
        'post_parent' => $post->ID, 
        'post_status' => 'inheret',
        'post_type'   => 'attachment',
        'post_mime_type' => 'image'
    ));

    if(isset($images)){
        foreach($images as $image){
            $imgThumb = wp_get_attachment_image_src($image->ID, $size, false);
            $urls[] = $imgThumb[0];
        }  

        return $urls;
    }else{
        return false;
    }
}

这将返回一个数组,其中包含附加到帖子/页面的每个图像 url。要循环显示&lt;ul&gt; 中的所有图像,您可以执行以下操作。

<?php if(have_posts()): while(have_posts()): the_post(); ?>
    <ul id="post_images">
        <?php $postImages = getPostImages($size = 'full'); ?>
        <?php foreach($postImages as $image): ?>
            <li><img src="<?php echo $image; ?>" /></li>
        <?php endforeach; ?>
    </ul>
<?php endwhile; endif; ?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-20
    • 2011-12-28
    • 2016-05-04
    • 1970-01-01
    相关资源
    最近更新 更多