📜  the_post_thumbnail - PHP (1)

📅  最后修改于: 2023-12-03 14:47:58.092000             🧑  作者: Mango

The Post Thumbnail - PHP

The Post Thumbnail, also known as Featured Image, is a built-in WordPress feature that allows users to upload and display an image for a post or page. The function the_post_thumbnail() can be used to display this image in the template files.

Syntax
the_post_thumbnail( $size, $attr );
  • $size (optional): size of the displayed image. This parameter can accept three different values:
    • String: registered image size name (e.g., "medium", "large", "thumbnail")
    • Array: an array with width and height values (e.g., array(150,150))
    • Boolean: false (use the original image size)
  • $attr (optional): additional attributes to be included in the img tag, such as CSS classes or IDs.
Usage

To use the_post_thumbnail() function in your template files, you will need to make sure that your theme has support for post thumbnails by adding the following line of code to the functions.php file:

add_theme_support( 'post-thumbnails' );

Once you have added this line of code, you can use the function the_post_thumbnail() to display the featured image in your template files. For example, if you want to display the feature image for the current post or page with a width of 500 pixels, you can use the following code:

<?php the_post_thumbnail( array(500,500) ); ?>

Alternatively, you can use the get_the_post_thumbnail() function to return the image HTML as a string, rather than outputting it directly. For example, the following code will return the HTML for the featured image with a width of 500 pixels:

<?php $thumbnail = get_the_post_thumbnail( null, array(500,500) );
if( !empty($thumbnail) ): ?>
    <?php echo $thumbnail; ?>
<?php endif; ?>
Conclusion

In conclusion, the_post_thumbnail() and get_the_post_thumbnail() functions are powerful tools that allow WordPress users to easily display featured images in their template files. Their simple syntax and versatility make them an essential part of any WordPress site's template files.