Skip to content
Menu
莱风 莱风
  • 序章
莱风 莱风

如何在wordpress首页自动显示每个文章内容的第一个图片

Posted on 2019/11/142024/02/13 by zhou

1.编辑当前主题的functions.php

//获取文章第一张图片,如果没有图就会显示默认的图
 function catch_that_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)){  
        $first_img = bloginfo('template_url'). '/images/default-thumb.jpg'; 
    } 
    return $first_img; 
 } 
2. 首页是index.php生成的,我们能看到以下代码,
<?php get_template_part( 'content', get_post_format() ); ?>
说明是根据文章类型来生成的内容,不同文章类型的内容生成文件一般是content*.php的文件
编辑对应的content*.php文件
<div class="entry-content">
            <a href="<?php the_permalink(); ?>"><img src="<?php echo catch_that_image() ?>" alt="<?php the_title(); ?>"/></a>  //增加这一行即可
            <?php if ( post_password_required() ) : ?>

发表回复 取消回复

您的邮箱地址不会被公开。 必填项已用 * 标注

4 + 8 = ?

近期文章

  • redhat Linux centos7 安装或卸载官方MySQL8
  • WordPress文章游客评论时添加验证码
  • 宝塔面板MySQL设置单数据库主从双向同步
  • wordpress修改底部版权信息删除RSS订阅按钮
  • centos7安装sql server 2022

分类

  • docker (4)
  • Linux (2)
  • MySQL (1)
  • sql (8)
  • Windows (5)
  • WordPress (5)
  • 未分类 (11)
  • 飞跃长城 (5)

近期评论

    其他操作

    • 登录
    ©2025 莱风