php 无论如何,获取WordPress帖子图片。必须在循环中使用。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php 无论如何,获取WordPress帖子图片。必须在循环中使用。相关的知识,希望对你有一定的参考价值。

<?php
/**
 * Echo an image, no matter what.
 *
 * @param string  $size  the image size you want to echo
 */
function wds_do_post_image( $size = 'thumbnail' ) {

	// If featured image is present, use that
	if ( has_post_thumbnail() ) {
		return the_post_thumbnail( $size );
	}

	// Check for any attached image
	$media = get_attached_media( 'image', get_the_ID() );
	$media = current( $media );

	// Set up default image path
	$media_url = get_stylesheet_directory_uri() . '/images/placeholder.png';

	// If an image is present, then use it
	if ( is_array( $media ) && 0 < count( $media ) ) {
		$media_url = ( 'thumbnail' === $size ) ? wp_get_attachment_thumb_url( $media->ID ) : wp_get_attachment_url( $media->ID );
	}

	echo '<img src="' . esc_url( $media_url ) . '" class="attachment-thumbnail wp-post-image" alt="' . esc_html( get_the_title() )  . '" />';
}
/**
 * Return an image URI, no matter what.
 *
 * @param  string  $size  The image size you want to return.
 * @return string         The image URI.
 */
function wds_skype_get_post_image_uri( $size = 'thumbnail' ) {

	// If featured image is present, use that.
	if ( has_post_thumbnail() ) {

		$featured_image_id = get_post_thumbnail_id( get_the_ID() );
		$media = wp_get_attachment_image_src( $featured_image_id, $size );

		if ( is_array( $media ) ) {
			return current( $media );
		}
	}

	// Set a placeholder image.
	$media_url = get_stylesheet_directory_uri() . '/assets/images/placeholder.png';

	// Check for any attached image.
	$media = get_attached_media( 'image', get_the_ID() );
	$media = current( $media );

	// If there's media attached to the post, use it.
	if ( $media && is_array( $media ) && 0 < count( $media ) ) {
		return current( wp_get_attachment_image_src( $media->ID, $size ) );
	}

	// If we've made it this far, we're gonna need a global.
	global $post;

	// Scan the post content, and pluck the first image URI.
	preg_match_all( '/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $image );

	// If there's an image and an image URL.
	if ( is_array( $image ) && array_key_exists( '0', $image[1] ) ) {

		// Grab the image ID from URL.
		$media_ID = _s_get_attachment_id_from_url( current( $image[1] ) );

		// If the image ID exists...
		if ( is_numeric( $media_ID ) ) {

			// Return the appropriate image size.
			return current( wp_get_attachment_image_src( $media_ID, $size ) );
		}
	}

	// If all else fails, return the placeholder.
	return $media_url;
}

以上是关于php 无论如何,获取WordPress帖子图片。必须在循环中使用。的主要内容,如果未能解决你的问题,请参考以下文章

PHP Wordpress - 获取帖子的第一张图片(没有自定义字段)

PHP Wordpress;从帖子中获取第一张图片并显示它

如何在没有 single.php 的情况下从 wordpress 帖子中删除特色图片

如何从 wordpress 中的帖子页面 id 获取 acf 的画廊图片 url

Wordpress如何获取图形标签内的帖子缩略图

如何从 Wordpress 页面/帖子中获取所有标签作为简码列表?