调用文章内部所有图片

2020-04-21  本文已影响0人  Stonesy

1.找到Appearance-->Theme Editor-->functions.php 加入以下代码

function get_all_image() {
global $post;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches,PREG_SET_ORDER);
return $matches[0][0];//文章里面所有图片  String
return $matches[1][0];//文章里面所有图片  String
}

2.在文章页面调用

.list{
            margin:6% auto;
            width:96%;
            max-width:1200px;
            overflow:hidden;
            list-style:none;
        }
        .list li{
            float:left;
            width:30%;
            margin-left:3.3%;
        }
        .list li:nth-child(3n+1){
            margin-left:0;
        }
        .list li a{
            display:block;
        }
        .list li a span{
            ext-overflow:ellipsis; 
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 1;
            overflow: hidden;
            margin-bottom:2%;
        }
        .list li a p {
            ext-overflow:ellipsis; 
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 3;
            overflow: hidden;
            text-align:justify;
            margin-bottom: 12px;
        }
        .list li a img{
            width:32.1%;
            margin-bottom:2%;
            height:auto;
            display:none;
        }
            .list li a img:first-child{
                width:100%;
                display:block;
            }
            .list li a img:first-child+img,
            .list li a img:first-child+img+img,
            .list li a img:first-child+img+img+img{
                display:inline-block;
            }
<ul class="list">
<?php
$args = array( 'numberposts' => 5, 'orderby' => 'rand', 'post_status' => 'publish' );
$rand_posts = get_posts( $args );
foreach( $rand_posts as $post ) : ?>
   <li>
   <a href="<?php the_permalink(); ?>">
   <?php the_excerpt();?>
       <div class="img_box"><?php echo get_all_image()?></div>
   </a>
   </li>
<?php endforeach; ?>
  </ul>
上一篇 下一篇

猜你喜欢

热点阅读