【问题标题】:Get images from wordpress post (post content)从 wordpress 帖子中获取图片(帖子内容)
【发布时间】:2018-06-30 19:06:51
【问题描述】:

我需要在 wordpress 中获取帖子的第一张图片。 我有各种各样的帖子。所以对于新帖子,我可以设置特色图片。但是有成千上万的旧帖子。我需要从这些帖子中提取第一张图片,以便我可以使用它们来显示。

我使用了来自http://css-tricks.com/snippets/wordpress/get-the-first-image-from-a-post/ 的代码,我认为它不适合我。

global $post;
$args = array( 'posts_per_page' => 10, 'category' => 6 );
$myposts = get_posts( $args );
foreach( $myposts as $post ) : setup_postdata($post);
......
.....
endforeach;

我需要以缩略图的形式显示每个帖子中的图像,就像在画廊中一样。我搜索了很多,但无法弄清楚如何。

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    把这个放在你的functions.php

    function getTheFirstImage() {
        $files = get_children('post_parent='.get_the_ID().'&post_type=attachment&post_mime_type=image');
        if($files) :
            $keys = array_reverse(array_keys($files));
            $j=0; $num = $keys[$j];
            $image=wp_get_attachment_image($num, 'large', false);
            $imagepieces = explode('"', $image);
            $imagepath = $imagepieces[1];
            $thumb=wp_get_attachment_thumb_url($num);
            echo "<img src='$thumb' class='thumbnail' />";
        endif;
    }
    

    然后在您要打印图像的模板中使用getTheFirstImage() 函数

    $args = array( 'posts_per_page' => 10, 'category' => 6 );
    $myposts = get_posts( $args );
    foreach( $myposts as $post ) : setup_postdata($post);
        getTheFirstImage(); // Will print the image
        ......
        .....
    endforeach;
    

    Check this forum post.

    【讨论】:

    • 一篇文章怎么样。假设我想获取我知道 ID 的帖子的图像。 $post-&gt;ID=12 现在我想要这篇文章的 post_content 中的图片
    • 然后只需传递 id $files = get_children('post_parent=2&amp;post_type=attachment&amp;post_mime_type=image');
    • @Heera : 请问怎么不能得到全尺寸的图片?
    • &lt;img src='$thumb' class='thumbnail' ./&gt; 中删除class=thumbnail
    猜你喜欢
    • 1970-01-01
    • 2011-12-28
    • 2013-07-27
    • 2016-05-04
    • 2010-12-04
    • 1970-01-01
    • 1970-01-01
    • 2013-10-09
    • 1970-01-01
    相关资源
    最近更新 更多