WordPress获取文章内容第一张图片

文章描述:

WordPress如何在文章内容页里面获取第一张图片并且显示?

自定义方法

functions.php

function catch_first_image() {
    global $post, $posts;
    $first_img = \'\';
    ob_start();
    ob_end_clean();
    $output = preg_match_all(\'/<img.+src=[\\\'\"]([^\\\'\"]+)[\\\'\"].*>/i\', $post->post_content, $matches);
    $first_img = $matches [1] [0];
    if(empty($first_img)) {
        //Defines a default image
        $first_img = \"/wp-content/themes/myui/images/default.jpg\";
    }
    return $first_img;
}

主题

single.php

<img src=\"<?php echo catch_first_image() ?>\"/>

 

© 版权声明
THE END
点赞0打赏 分享
评论 抢沙发

请登录后发表评论

    请登录后查看评论内容