Jus*_*ine 4 php wordpress image function
我在一些博客上找到了这段代码,它应该显示来自WordPress帖子的所有图像.
function getImage() {
global $more;
$more = 1;
$link = get_permalink();
$content = get_the_content();
$count = substr_count($content, '<img');
$start = 0;
for($i=1;$i<=$count;$i++) {
$imgBeg = strpos($content, '<img', $start);
$post = substr($content, $imgBeg);
$imgEnd = strpos($post, '>');
$postOutput = substr($post, 0, $imgEnd+1);
$postOutput = preg_replace('/width="([0-9]*)" height="([0-9]*)"/', '',$postOutput);;
if(stristr($postOutput,'<img')) { echo $postOutput; }
$start=$imgEnd+1;
}
$more = 0;
}
Run Code Online (Sandbox Code Playgroud)
但是会发生什么......它正确地显示第一和第二图像,然后循环第二个图像而不是第三个图像等.它可以抓取图像的数量,但不显示第1,第2,第3,第4个图像,它显示第1个,第2,第2,第2 ......
任何人都可以看看这个片段,也许想出为什么会发生这种情况?我知道代码相当邋,,但我只是在一些博客上找到它,作为一个PHP新手和所有:)
所有帮助表示感谢,提前感谢!
$attachments = get_children(array('post_parent' => $post->ID,
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'image',
'order' => 'ASC',
'orderby' => 'menu_order ID'));
foreach($attachments as $att_id => $attachment) {
$full_img_url = wp_get_attachment_url($attachment->ID);
// Your Code here
}
Run Code Online (Sandbox Code Playgroud)
您也可以在这里查看:http: //www.rlmseo.com/blog/get-images-attached-to-post/
现在使用新的 wordpress get_attached_media($type,$post)函数更容易
$attachments= get_attached_media( 'image', $post->ID );
foreach($attachments as $att_id => $attachment) {
$full_img_url = wp_get_attachment_url($attachment->ID);
// You can echo it out here
}
Run Code Online (Sandbox Code Playgroud)
请注意,这只会获取上传到帖子的文件。不是通过媒体库添加的文件。