Home > CMS Tutorial > WordPress > body text

How does WordPress automatically extract the first image in the content as a thumbnail?

藏色散人
Release: 2020-01-02 09:45:01
Original
2548 people have browsed it

How does WordPress automatically extract the first image in the content as a thumbnail?

How does WordPress automatically extract the first picture in the content as a thumbnail?

The example in this article tells how WordPress automatically A method of extracting the first image in the content as a thumbnail. Share it with everyone for your reference. The specific analysis is as follows:

Recommendation: "wordpress tutorial"

Sometimes we do not have thumbnails when publishing articles, and we hope that the system will automatically extract our The first picture in the published article content is used as a thumbnail. Now I will introduce to you how WordPress automatically extracts the first picture in the content as a thumbnail. Students who need to know more can refer to it.

In php We can use preg_match and preg_match_all to obtain the addresses of all images in the content.

Step 1: Add the following function in function.php of the theme template, the code is as follows:

The code is as follows:

//截取内容中第一张图片函数 
function catch_that_image() { 
global $post, $posts; 
ob_start(); 
ob_end_clean(); 
preg_match(&#39;/<imgs[^<>]*?src=[&#39;"]([^&#39;"<>]+?)[&#39;"][^<>]*?>/i&#39;, $post->post_content, $matche); 
if($matche[1]) 
return $matche[1]; 
//否则取默认图片 
return &#39;default.gif&#39;; 
}
Copy after login

Step 2: Use this function directly where WordPress needs to call thumbnails, as in the example below, the code is as follows:

The code is as follows:

<img src="<?php echo catch_that_image(); ?>" alt="<?php the_title(); ?>" title="<?php the_title(); ?>" width="200px" height="200px" />
Copy after login

I hope this article The above will be helpful to everyone’s WordPress website building.

The above is the detailed content of How does WordPress automatically extract the first image in the content as a thumbnail?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template