php - 从wordpress帖子中获取图片(帖子内容)

标签 php wordpress

我需要在 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;

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

最佳答案

将其放入您的 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 .

关于php - 从wordpress帖子中获取图片(帖子内容),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17353100/

相关文章:

php - 在 MVC 网站中验证和处理表单提交的位置

css - WP Twentyseventeen 菜单颜色更改不起作用

PHP - 为移动 View 使用预格式化的 html

php - 用产品自定义字段值覆盖 woocommerce 购物车项目价格

css - Wordpress:突出显示事件菜单项

wordpress - 同一页面上的多个 Vue 实例使用相同的代码库

php - 搜索结果中的 WordPress 面包屑

php - 不断收到 fatal error :调用未定义的方法 DB::prepare()

php - 从 C++ 程序调用 PHP 脚本

php - 使用基于浏览器的 YouTube API 客户端身份验证时,oauth2 的重定向 URI 片段中有额外的字段