WordPress 通过文章ID获取第一张图片

网站APP 6 个月前 回复

, , ,

WordPress 通过文章ID获取第一张图片

<?php
/**
 * Echo first image (if available).
 *
 * @param int $post_id Post ID.
 */
function wpdocs_echo_first_image( $post_id ) {
	$args = array(
		'posts_per_page' => 1,
		'order'          => 'ASC',
		'post_mime_type' => 'image',
		'post_parent'    => $post_id,
		'post_status'    => null,
		'post_type'      => 'attachment',
	);

	$attachments = get_children( $args );

	if ( $attachments ) {
		foreach ( $attachments as $attachment ) {
			$image_attributes = wp_get_attachment_image_src( $attachment->ID, 'thumbnail' ) ? wp_get_attachment_image_src( $attachment->ID, 'thumbnail' ) : wp_get_attachment_image_src( $attachment->ID, 'full' );
			echo '<img src="' . esc_url( wp_get_attachment_thumb_url( $attachment->ID ) ) . '" class="current" />';
		}
	}
}

原文参考 https://developer.wordpress.org/reference/functions/get_children/#comment-1306

支付宝打赏微信打赏

如果此文对你有帮助,欢迎打赏作者。

发表评论

欢迎回来 (打开)

(必填)