首页 文章

php - 从 wordpress 帖子获取图片网址

提问于
浏览
0

我有基于 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]);
}

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

1 回答

  • 0

    这可能会帮到你,这是一个可以放入 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 都附加到 post/page。要循环播放并显示<ul>中的所有图像,您可以执行类似的操作。

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

相关问题